• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Exception doubt

 
Nik Arora
Ranch Hand
Posts: 652
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi All,
The output for the below code is BAFF.Can anybody explain me how?

class ExceptionA extends Exception {}
class ExceptionB extends ExceptionA {}

public class ObjectTest {

public static void main(String[] args) {
try {
throw new ExceptionB();
} catch (ExceptionB b) {
System.out.print("B");
try {
throw new ExceptionB();
} catch (ExceptionA e) {
System.out.print("A");
} finally {
System.out.print("F");
}
} catch (ExceptionA a) {
System.out.print("A");
} finally {
System.out.print("F");
}
}
}
Source:TeamTesting

Thanks All
 
Chandra Bhatt
Ranch Hand
Posts: 1710
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
First of all no problem with code, compiles and runs fine.



Where was your doubt exactly?

Thanks,
 
Keith Lynn
Ranch Hand
Posts: 2409
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator


An ExceptionB object is thrown in line 8 and is caught by the catch block in line 9 causing B to be printed.

An ExceptionB object is thrown in line 13, and since ExceptionB is a subclass of ExceptionA, it is caught by the catch block in line 14, causing an A to be printed.

Since a finally block is always executed unless the JVM shuts down, an F is printed.

Then the finally block associated with the first try is executed causing another F to be printed.
[ May 08, 2007: Message edited by: Keith Lynn ]
 
Nik Arora
Ranch Hand
Posts: 652
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
THANKS K
 
Nik Arora
Ranch Hand
Posts: 652
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thanks keith
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic