MCQs
None.
Output:
$ javac exception_handling.java
$ java exception_handling
B
There is no exception thrown, so all the code with the exception of the catch statement block is run.
try block is throwing NullPointerException but the catch block is used to counter
Arithmetic Exception. Hence NullPointerException occurs since no catch is there
which can handle it, runtime error occurs.
Output:
$ javac exception_handling.java
$ java exception_handling
Exception in thread "main" java.lang.NullPointerException: Hello
None.
Output:
$ javac exception_handling.java
$ java exception_handling
Exception in thread "main" java.lang.ArithmeticException: / by zero
World
None.
Output:
$ javac exception_handling.java
$ java exception_handling
1
What will be the output of the program?
public class Test
{
public static void aMethod() throws Exception
{
try /* Line 5 */
{
throw new Exception(); /* Line 7 */
}
finally /* Line 9 */
{
System.out.print("finally "); /* Line 11 */
}
}
public static void main(String args[])
{
try
{
aMethod();
}
catch (Exception e) /* Line 20 */
{
System.out.print("exception ");
}
System.out.print("finished"); /* Line 24 */
}
}
This is what happens:
(1) The execution of the try block (line 5) completes abruptly because of the throw statement
(line 7).
(2) The exception cannot be assigned to the parameter of any catch clause of the try statement
therefore the finally block is executed (line 9) and "finally" is output (line 11).
(3) The finally block completes normally, and then the try statement completes abruptly because of the throwstatement (line 7).
(4) The exception is propagated up the call stack and is caught by the catch in the main method (line 20).
This prints "exception".
(5) Lastly program execution continues, because the exception has been caught, and "finished" is output
(line 24).
None.
What will be the output of the program?
public class RTExcept
{
public static void throwit ()
{
System.out.print("throwit ");
throw new RuntimeException();
}
public static void main(String [] args)
{
try
{
System.out.print("hello ");
throwit();
}
catch (Exception re )
{
System.out.print("caught ");
}
finally
{
System.out.print("finally ");
}
System.out.println("after ");
}
}
The main() method properly catches and handles the RuntimeException in the catch block,
finally runs (as it always does), and then the code returns to normal.
A, B and C are incorrect based on the program logic described above. Remember that properly
handled exceptions do not cause the program to stop executing.
ArrayIndexOutOfBoundsException is a built in exception that is caused when we try
to access an index location which is beyond the length of an array.
None.