Java Programming - Exceptions - Discussion
Discussion Forum : Exceptions - Finding the output (Q.No. 3)
3.
What will be the output of the program?
public class X
{
public static void main(String [] args)
{
try
{
badMethod();
System.out.print("A");
}
catch (Exception ex)
{
System.out.print("B");
}
finally
{
System.out.print("C");
}
System.out.print("D");
}
public static void badMethod()
{
throw new Error(); /* Line 22 */
}
}
Answer: Option
Explanation:
Error is thrown but not recognised line(22) because the only catch attempts to catch an Exception and Exception is not a superclass of Error. Therefore only the code in the finally statement can be run before exiting with a runtime error (Exception in thread "main" java.lang.Error).
Discussion:
29 comments Page 2 of 3.
Hritika said:
10 years ago
Isn't is mandatory to use throws keyword with bad method () if throw keyword is used in the method definition. ?
Prithiv said:
9 years ago
I didn't get this, Can anyone explain this clearly?
James said:
9 years ago
Why is it not printing "A" here?
Sonika said:
9 years ago
Anyone exlain the hierarchy of exception handling for me please.
Sonika said:
9 years ago
What is the relation between error and exception?
Suma said:
9 years ago
@Sonika.
Throwable is the parent class, exception and error are subclass of throwable.
Throwable is the parent class, exception and error are subclass of throwable.
Sachith said:
9 years ago
Can anyone explain why this line not execute "System.out. print("D") ;"?
Ammu said:
9 years ago
Can't understand. So please explain me clearly.
Vijay said:
8 years ago
I couldn't get it, can someone help me out?
Anoms said:
8 years ago
Here is an explanation why 'C' is the answer.
1. The class is instantiated.
2. Going to try() block.
3. badMethod() is called.
4. badMethod() throwing an Error.
5. Going back to try() block, it doesn't have anything to handle the Error because Exceptions and Errors two separate things.
6. The catch (Exception ex) only catches exceptions, not errors.
7. Finally() block is executed...ALWAYS!!!(No matter what happened in the try() & catch() blocks).
8. C is printed then the error message get printed.
1. The class is instantiated.
2. Going to try() block.
3. badMethod() is called.
4. badMethod() throwing an Error.
5. Going back to try() block, it doesn't have anything to handle the Error because Exceptions and Errors two separate things.
6. The catch (Exception ex) only catches exceptions, not errors.
7. Finally() block is executed...ALWAYS!!!(No matter what happened in the try() & catch() blocks).
8. C is printed then the error message get printed.
(1)
Post your comments here:
Quick links
Quantitative Aptitude
Verbal (English)
Reasoning
Programming
Interview
Placement Papers