MCQs
What will be the output of the program?
public class X
{
public static void main(String [] args)
{
try
{
badMethod();
System.out.print("A");
}
catch (RuntimeException ex) /* Line 10 */
{
System.out.print("B");
}
catch (Exception ex1)
{
System.out.print("C");
}
finally
{
System.out.print("D");
}
System.out.print("E");
}
public static void badMethod()
{
throw new RuntimeException();
}
}
A Run time exception is thrown and caught in the catch statement on line 10. All the code
after the finally statement is run because the exception has been caught.
None.
None.
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 */
}
}
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).
Error class is related to java run time error that can't be caught usually,
RuntimeExecption is subclass of Exception class which contains all the
exceptions that can be caught.
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).
Error class is related to java run time error that can't be caught usually,
RuntimeExecption is subclass of Exception class which contains all the
exceptions that can be caught.
finally keyword is used to define a set of instructions that will be executed irrespective
of the exception found or not.
try block can be followed by any of finally or catch block, try block checks for exceptions
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:
1. An exception arising in the finally block itself.
2. The death of the thread.
3. The use of System.exit()
4. Turning off the power to the CPU.
I suppose the last three could be classified as VM shutdown.