Win a copy of Svelte and Sapper in Action this week in the JavaScript forum!
  • 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 all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Ron McLeod
  • Paul Clapham
  • Bear Bibeault
  • Junilu Lacar
Sheriffs:
  • Jeanne Boyarsky
  • Tim Cooke
  • Henry Wong
Saloon Keepers:
  • Tim Moores
  • Stephan van Hulst
  • Tim Holloway
  • salvin francis
  • Frits Walraven
Bartenders:
  • Scott Selikoff
  • Piet Souris
  • Carey Brown

Exception thrown from catch and finally block...

 
Ranch Hand
Posts: 418
  • Mark post as helpful
  • send pies
  • 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
  • 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.
 
Bring me the box labeled "thinking cap" ... and then read this tiny ad:
the value of filler advertising in 2020
https://coderanch.com/t/730886/filler-advertising
    Bookmark Topic Watch Topic
  • New Topic