wood burning stoves 2.0*
The moose likes Beginning Java and the fly likes Exceptions Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of Murach's Java Servlets and JSP this week in the Servlets forum!
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "Exceptions" Watch "Exceptions" New topic
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: 60739
    
  65

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


[Asking smart questions] [Bear's FrontMan] [About Bear] [Books by 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
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: Exceptions
 
Similar Threads
Try catch finally query
Finally block
Exceptions
Exception
Is finally, really finally