This week's book giveaway is in the Clojure forum.
We're giving away four copies of Clojure in Action and have Amit Rathore and Francis Avila on-line!
See this thread for details.
Win a copy of Clojure in Action this week in the Clojure forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Exceptions

 
Tetsuo Suzuki
Greenhorn
Posts: 22
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Pie
Posts: 64185
83
IntelliJ IDE Java jQuery Mac Mac OS X
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
 
Mike Curwen
Ranch Hand
Posts: 3695
IntelliJ IDE Java Ubuntu
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 47
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator

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
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic