• Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other Pie Elite all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Jeanne Boyarsky
  • Ron McLeod
  • Paul Clapham
  • Liutauras Vilda
Sheriffs:
  • paul wheaton
  • Rob Spoor
  • Devaka Cooray
Saloon Keepers:
  • Stephan van Hulst
  • Tim Holloway
  • Carey Brown
  • Frits Walraven
  • Tim Moores
Bartenders:
  • Mikalai Zaikin

Exception thrown from catch and finally block...

 
Ranch Hand
Posts: 418
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
I tried out following code ...
public class Ex3
{
void method()throws MyException
{
try {
throw new MyException("UnExpected Conditions!");
}
catch(MyException e){
System.out.println("In the method -caught- " + e);
throw new MyException("Exception thrown from catch block");
}
finally
{
System.out.println("finally in the method...");
throw new MyException("Exception thrown from finally block");
}
}
public static void main(String args[]){
Ex3 o = new Ex3();
try {
o.method();
}

catch(MyException e)
{
System.out.println("caught- " + e);

}

System.out.println("exiting main...");
}
}
class MyException extends Exception
{
public MyException(){}
public MyException(String msg){
super(msg);
}
}
The o/p is
In the method -caught- MyException: UnExpected Conditions!
finally in the method...
caught- MyException: Exception thrown from finally block
exiting main...

What happens about Exception thrown by catch block in the method? Catch in main catches the exception thrown by finally block in method. Who handles the Exception thrown by catch block in method?
Rashmi
 
Ranch Hand
Posts: 1492
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Hi Rashmi,
The exception thrown from the catch block is overwritten with the one thrown in the finally block. Your method can only throw one exception and the last one wins.
Since the finally method is guaranteed to be executed, it will always be after anything happening in a catch block.
Regards,
Manfred.
 
reply
    Bookmark Topic Watch Topic
  • New Topic