| Author |
Exceptions
|
Tetsuo Suzuki
Greenhorn
Joined: Feb 21, 2002
Posts: 22
|
|
Hey all, a few questions about exception handling in java. First off: I understand that the finally{} block is meant to execute regardless of success or failure in the try{} block. So if I have the following: This is by the book but strangely enough if I have the following: Are there only certain circumstances where the finally block is essential to run code after an exception has been caught in a catch block? Or is it a matter of surety that code will run regardless of success or failure? Question 2: If I have a method: I get a compile error if I try to use the method without an exception handler. BUT... if I have a method: Java lets me compile without an exception handler when calling the method. Wierd, has anyone else run into this? Tetsuo!
|
 |
Bear Bibeault
Author and ninkuma
Marshal
Joined: Jan 10, 2002
Posts: 56529
|
|
You have some basic misunderstandings of the mechanisms. In your example: try{ //blah }catch(Exception e){ //blah } System.out.println("This always occurs"); // the above runs *anyway*, without the finally{} The output statement will execute as part of the normal flow within the method. When you catch an exception as shown here, flow continues normally after the try/catch/finally block. If you did not catch the exception, or if you threw another exception in your handler, the output statement would not be called in this example, but would be called if it was in a finally block. hth, bear
|
[Smart Questions] [JSP FAQ] [Books by Bear] [Bear's FrontMan] [About Bear]
|
 |
Mike Curwen
Ranch Hand
Joined: Feb 20, 2001
Posts: 3695
|
|
As for #2: NumberFormatException is a subclass of java.lang.IllegalArgumentException, which in turn, is a type of java.lang.RuntimeException. Reading the API for this exception type, we find:
|
 |
Alex Ku
Ranch Hand
Joined: Jan 15, 2002
Posts: 47
|
|
Are there only certain circumstances where the finally block is essential to run code after an exception has been caught in a catch block? Or is it a matter of surety that code will run regardless of success or failure?
here is an example in the above, since there is a return statement with catch. Once there is an exception, cleanup 2 is not executed. But cleanup 1 will be executed if there is an exception or not. kawaii
|
 |
 |
|
|
subject: Exceptions
|
|
|