Here I have used throws in method signature when i am going to call this method from some where else that is not asking me to handle the exception.

 public class Exception {

        int a, b, c;

        void set(String data[]) throws NumberFormatException, ArrayIndexOutOfBoundsException {
            a = Integer.parseInt(data[0]);//convert the string into int. eg1.("12" ---> 12)  eg2.("df23" ---> fail)
            b = Integer.parseInt(data[1]);
            c = 0;
        }

        void divide() throws ArithmeticException {
            c = a / b;
        }

        void disp() {
            System.out.println(a + " / " + b + " = " + c);
        }
    }
有帮助吗?

解决方案

when i am going to call this method from some where else that is not asking me to handle the exception.

Yes, because both are RuntimeExceptions and must not be caught.

Read the java tutorial about exceptions and unchecked exceptions.

Sometimes you see methods that declare RuntimeExceptions, like your method does. It is a way to document the exceptions that might be thrown even if you don't catch them.

In addition to user3168013's comment

how can we able to convert unchecked exception to checked exception .

Every exception can have a cause. A cause is another exception that lead to it. If it has no cause it is a root exception. So you can just create an instance of a checked exception, pass it the unchecked exception as it's cause and throw the checked expection.

For example define your checked exception

public class DataFormatException extends Exception {
    public DataFormatException(Throwable cause) {
        super(cause);
    }
}

and then throw your own

void set(String data[]) throws DataFormatException {
    try {
        a = Integer.parseInt(data[0]);// convert the string into int.
                                        // eg1.("12"
                                        // ---> 12) eg2.("df23" ---> fail)
        b = Integer.parseInt(data[1]);
        c = 0;
    } catch (NumberFormatException e) {
        throw new DataFormatException(e);
    } catch (ArrayIndexOutOfBoundsException e) {
        throw new DataFormatException(e);
    }
}

Of course it would be better to give a detailed exception message depending on the cause, but this is just a short example.

其他提示

Both Exceptions are unchecked Exception. Unchecked Exception are handled at runtime.

Its developer choice how to handle or not runtime Exception , compiler never force you handle.

Find more on handling Runtime Exception.

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top