Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Handling checked exceptions

I'm reading exception handling in the book "A programmer guide to Java SCJP certificate". The author wrote that :

If a checked exception is thrown in a method, it must be handled in one of three ways:

1.By using a try block and catching the exception in a handler and dealing with it

2.By using a try block and catching the exception in a handler, but throwing another exception that is either unchecked or declared in its throws clause

3.By explicitly allowing propagation of the exception to its caller by declaring it in the throws clause of its method header

I understood clearly the first and third, but the second made me a lot of confused. My concerns are that :

-It's still alright even if I don't throw any other unchecked exceptions, so why do we have to throw another exception at here?

-Why do we have to re-declare the exception that we have caught, in throws clause? I think it's over by the handler.

Thanks to everyone.

like image 917
Hung Tran Avatar asked Jun 12 '11 01:06

Hung Tran


2 Answers

The book just list three allowed options.

-It's still alright even if I don't throw any other unchecked exceptions, so why do we have to throw another exception at here?

You might want to throw another more descriptive exception, for example adding more info.

-Why do we have to re-declare the exception that we have caught, in throws clause? I think it's over by the handler.

You don't have to re-declare. But if the new exception you are throwing is checked, then you must declare it in the throws clause. In fact the exception you just caught doesn't need to be declared even if checked.

like image 153
Petar Ivanov Avatar answered Sep 23 '22 02:09

Petar Ivanov


You may want to do this to catch a checked exception and throw another checked exception of a different kind. Perhaps you want to throw your own exception rather than a different one.

public void doSomething() throws MyCheckedException {
    try {
        doSomethingThatThrowsSpecificCheckedException();
    } catch(SpecificCheckedException e) {
        throw new MyCheckedException();
    }
}

Or you can throw an unchecked exception (something that is or extends RuntimeException).

public void doSomething() {
    try {
        doSomethingThatThrowsSpecificCheckedException();
    } catch(SpecificCheckedException e) {
        throw new RuntimeException();
    }
}
like image 23
nicholas.hauschild Avatar answered Sep 21 '22 02:09

nicholas.hauschild