• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

A runtime exception is throws in the catch clause:

 
Thomas Markl
Ranch Hand
Posts: 192
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 40
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
 
Jim Yingst
Wanderer
Sheriff
Posts: 18671
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic