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 3 of 3.
Murali said:
8 years ago
I have executed the above program.
And I got output only error message and "C" is not printed.
Can anyone explain the flow?
Thank you.
And I got output only error message and "C" is not printed.
Can anyone explain the flow?
Thank you.
Khagendra said:
8 years ago
Thanks @Anoms for brief explanation.
Divyaja said:
7 years ago
Why D is not printed?
Bindu said:
7 years ago
Why A is not printed here? Please explain in detail.
Newton said:
7 years ago
@Bindu.
Before the compiler reaches the print statement for 'A', badMethod () is called where an error is created and now the compiler will go and check for any error handling methods, so A won't be printed.
Before the compiler reaches the print statement for 'A', badMethod () is called where an error is created and now the compiler will go and check for any error handling methods, so A won't be printed.
Matikana Rambabu said:
7 years ago
Can anyone explain why "D" is not printed? Please?
(1)
Sangeethar said:
7 years ago
I had compiled it & it shows as below.
CException in thread "main" java.lang.Error
at X.badMethod(X.java:22)
at X.main(X.java:7)
I had noted as if nothing got printed like"c".
Can anyone explain?
CException in thread "main" java.lang.Error
at X.badMethod(X.java:22)
at X.main(X.java:7)
I had noted as if nothing got printed like"c".
Can anyone explain?
(1)
Aishwarya said:
7 years ago
D is also printed because after finally{ } block all statements are executed.
Dzingai said:
3 years ago
Hello @Sangeethar and @Murali.
The "C" is actually printed but it is concatenated with the word Exception as "CException in thread. Java. Lang. Error". This is because the coder used "print() " instead of "println() ".
The "C" is actually printed but it is concatenated with the word Exception as "CException in thread. Java. Lang. Error". This is because the coder used "print() " instead of "println() ".
Post your comments here:
Quick links
Quantitative Aptitude
Verbal (English)
Reasoning
Programming
Interview
Placement Papers