Think Dream Create Inovate

Wednesday, June 8, 2011

Exceptions

1. What will be the output of the program?

public class Foo
{
public static void main(String[] args)
{
try
{
return;
}
finally
{
System.out.println( "Finally" );
}
}
}

A. Finally
B. Compilation fails.
C. The code runs with no output.
D. An exception is thrown at runtime.

Answer & ExplanationAnswer: Option A

Explanation:
If you put a finally block after a try and its associated catch blocks, then once execution enters the try block, the code in that finally block will definitely be executed except in the following circumstances:

An exception arising in the finally block itself.
The death of the thread.
The use of System.exit()
Turning off the power to the CPU.

2. What will be the output of the program?

try
{
int x = 0;
int y = 5 / x;
}
catch (Exception e)
{
System.out.println("Exception");
}
catch (ArithmeticException ae)
{
System.out.println(" Arithmetic Exception");
}
System.out.println("finished");

A. finished B. Exception
C. Compilation fails. D. Arithmetic Exception

Answer & ExplanationAnswer: Option C

Explanation:
Compilation fails because ArithmeticException has already been caught. ArithmeticException is a subclass of java.lang.Exception, by time the ArithmeticException has been specified it has already been caught by the Exception class.

If ArithmeticException appears before Exception, then the file will compile. When catching exceptions the more specific exceptions must be listed before the more general (the subclasses must be caught before the superclasses).

No comments:

Post a Comment