• 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:
  • Tim Cooke
  • Campbell Ritchie
  • Jeanne Boyarsky
  • Ron McLeod
  • Liutauras Vilda
Sheriffs:
  • Rob Spoor
  • Junilu Lacar
  • paul wheaton
Saloon Keepers:
  • Stephan van Hulst
  • Tim Moores
  • Tim Holloway
  • Carey Brown
  • Scott Selikoff
Bartenders:
  • Piet Souris
  • Jj Roberts
  • fred rosenberger

Exception doubt

 
Ranch Hand
Posts: 652
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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
 
Ranch Hand
Posts: 1710
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
First of all no problem with code, compiles and runs fine.



Where was your doubt exactly?

Thanks,
 
Ranch Hand
Posts: 2412
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
THANKS K
 
Nik Arora
Ranch Hand
Posts: 652
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Thanks keith
 
pie. tiny ad:
Building a Better World in your Backyard by Paul Wheaton and Shawn Klassen-Koop
https://coderanch.com/wiki/718759/books/Building-World-Backyard-Paul-Wheaton
reply
    Bookmark Topic Watch Topic
  • New Topic