Java MCQs on throw, throws & nested try of Java Programming Language.
1. Which of these keywords is used to generate an exception explicitly? Answer: c 2. Which of these class is related to all the exceptions that are explicitly thrown? Answer: c 3. Which of these operator is used to generate an instance of an exception than can be thrown by using throw? Answer: a 4. Which of these keywords is used to by the calling function to guard against the exception that is thrown by called function? Answer: c 5. What will be the output of the following Java code? a) TypeA Answer: c 6. What will be the output of the following Java code? a) A 7. What will be the output of the following Java code? a) Finally Answer: a 8. What will be the output of the following Java code? a) The program will not compile because no exceptions are specified Answer: d
a) try
b) finally
c) throw
d) catch
Clarification: None.
a) Error
b) Exception
c) Throwable
d) Throw
Clarification: None.
a) new
b) malloc
c) alloc
d) thrown
Clarification: new is used to create an instance of an exception. All of java’s built in run-time exceptions have two constructors: one with no parameters and one that takes a string parameter.
a) try
b) throw
c) throws
d) catch
Clarification: If a method is capable of causing an exception that it does not handle. It must specify this behaviour the behaviour so that callers of the method can guard themselves against that exception. This is done by using throws clause in methods declaration.
class exception_handling
{
public static void main(String args[])
{
try
{
int a = args.length;
int b = 10 / a;
System.out.print(a);
try
{
if (a == 1)
a = a / a - a;
if (a == 2)
{
int []c = {1};
c[8] = 9;
}
}
catch (ArrayIndexOutOfBoundException e)
{
System.out.println("TypeA");
}
catch (ArithmeticException e)
{
System.out.println("TypeB");
}
}
}
}
b) TypeB
c) Compile Time Error
d) 0TypeB
Clarification: Because we can’t go beyond array limit
class exception_handling
{
public static void main(String args[])
{
try
{
System.out.print("A");
throw new NullPointerException ("Hello");
}
catch(ArithmeticException e)
{
System.out.print("B");
}
}
}
b) B
c) Hello
d) Runtime Exception
Clarification: None.
Output:
$ javac exception_handling.java
$ java exception_handling
Exception in thread "main" java.lang.NullPointerException: Hello
at exception_handling.main
public class San
{
public static void main(String[] args)
{
try
{
return;
}
finally
{
System.out.println( "Finally" );
}
}
}
b) Compilation fails
c) The code runs with no output
d) An exception is thrown at runtime
Clarification: Because finally will execute always.
public class San
{
public static void main(String args[])
{
try
{
System.out.print("Hello world ");
}
finally
{
System.out.println("Finally executing ");
}
}
}
b) The program will not compile because no catch clauses are specified
c) Hello world
d) Hello world Finally executing
Clarification: None