문제

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