DBoth are identical; throws is just an older syntax
Correct Answer:
B. throw explicitly raises an exception, throws declares that a method may throw exceptions
EXPLANATION
'throw' is a statement that explicitly throws an exception object. 'throws' is a clause in method signature indicating the method may throw specific checked exceptions. Example: throw new IOException(); vs public void method() throws IOException {}
What is the output of the following code?
try {
int x = 10/0;
} catch(ArithmeticException e) {
System.out.println("Caught");
} finally {
System.out.println("Finally");
}
System.out.println("After");
ACaught\nFinally\nAfter
BCaught\nFinally
CFinally\nAfter
DArithmeticException is thrown, program terminates
Correct Answer:
A. Caught\nFinally\nAfter
EXPLANATION
When ArithmeticException occurs, it's caught by the catch block printing 'Caught'. The finally block always executes, printing 'Finally'. Then normal program flow continues, printing 'After'.
What will happen when the following code is executed?
try {
int[] arr = {1, 2, 3};
System.out.println(arr[5]);
} catch(ArrayIndexOutOfBoundsException e) {
System.out.println("Exception caught");
}
ACompilation error
BRuntime error without output
CException caught
DNo output
Correct Answer:
C. Exception caught
EXPLANATION
Accessing arr[5] when array has only 3 elements throws ArrayIndexOutOfBoundsException which is caught and 'Exception caught' is printed.
What is the correct syntax for declaring a method that throws a checked exception?
Apublic void method() throws IOException {}
Bpublic void method() catch IOException {}
Cpublic void method() try IOException {}
Dpublic void method() exceptions IOException {}
Correct Answer:
A. public void method() throws IOException {}
EXPLANATION
The 'throws' keyword is used in method declaration to indicate that the method might throw checked exceptions. Syntax: method() throws ExceptionType {}
What is the output of the following code?
int x = 10;
try {
x = x / 0;
} catch (ArithmeticException e) {
x = 20;
} finally {
x = 30;
}
System.out.println(x);
A10
B20
C30
DError: compilation fails
Correct Answer:
C. 30
EXPLANATION
The finally block always executes last and sets x to 30. The output will be 30 because finally block assignments override catch block assignments.
What will be the output?
public class Test {
public static void main(String[] args) {
try {
throw new Exception("Test");
} catch (Exception e) {
System.out.println("1");
} catch (Exception e) {
System.out.println("2");
}
}
}
A1
B1 2
CCompilation error
D2
Correct Answer:
C. Compilation error
EXPLANATION
Multiple catch blocks with the same exception type cause compilation error. Java doesn't allow duplicate catch blocks for identical exception types.