aspose file tools*
The moose likes Java in General and the fly likes A runtime exception is throws in the catch clause: Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Java in General
Bookmark "A runtime exception is throws in the catch clause:" Watch "A runtime exception is throws in the catch clause:" New topic
Author

A runtime exception is throws in the catch clause:

Thomas Markl
Ranch Hand

Joined: Mar 08, 2001
Posts: 192
I don’t understand this:
Both programs throw the Runtime-Exception „ArithmeticException“ in the catch clause.
But in Test81 the „finally“ clause prevents the ArithmeticException
From beeing thrown to the System level.
What happens?

Result:
C:\Java\EigeneJavaProgramme>java Test81
Peace

Why does it throw Arithmetic Exception NOW?


C:\Java\EigeneJavaProgramme>java Test81a
java.lang.ArithmeticException: / by zero
at Test81.raid(Test81a.java:11)
at Test81.main(Test81a.java:22)
Exception in thread "main"
Sam Zou
Ranch Hand

Joined: Nov 18, 2002
Posts: 40
Hi,
In fact the ArithmeticException is thrown in both case. To see it, put a try catch statement at the place where you make your zero division.
The ouput give :
E:\Dev\src\Test>java Test81
ArithmeticException
Peace MAIN
In your Test81 class, the ArithmeticEception doesn't come up because it is not catched by any catch statement.
The finally clause is always executed no matter what happened in the catch clause.
But I don't known why in Test81 the program don't stop to notice the ArithmeticException.
Waltereo


Sam<p>"Life is difficult"<br /> -Scott Peck-</p>
Jim Yingst
Wanderer
Sheriff

Joined: Jan 30, 2000
Posts: 18671
In Test81, the return statement inside the finally {} essentially tells the JVM to forget about the exception that it was throwing, and just return "Peace" instead. This is why it's almost always a bad idea to do a return inside a finally. Also if any new exception were thrown inside the finally, only the new exception would be thrown - the old one would be forgotten. This may seem strange, but what other behavior would make more sense? It's not possible to throw two exceptions, or to throw one exception and also return a value - so the language designers decided to make the JVM do whatever the finally clause says, inpreference to what would have happened otherwise.


"I'm not back." - Bill Harding, Twister
 
It is sorta covered in the JavaRanch Style Guide.
 
subject: A runtime exception is throws in the catch clause: