Recall & Review
beginner
What is the purpose of multiple catch blocks in Java?
Multiple catch blocks allow a program to handle different types of exceptions separately, providing specific responses for each exception type.
Click to reveal answer
beginner
How does Java decide which catch block to execute when an exception occurs?
Java checks the exception type thrown and matches it with the first compatible catch block in order. It executes the first matching catch block and skips the rest.
Click to reveal answer
beginner
Can you have multiple catch blocks for a single try block in Java?
Yes, you can have multiple catch blocks after a single try block to handle different exception types separately.
Click to reveal answer
intermediate
What happens if a more general exception catch block is placed before a more specific one?
The compiler will give an error because the more general catch block will catch all exceptions of that type and its subclasses, making the specific catch block unreachable.
Click to reveal answer
beginner
Write a simple Java try-catch example with multiple catch blocks for ArithmeticException and NullPointerException.
try {
int result = 10 / 0;
String text = null;
System.out.println(text.length());
} catch (ArithmeticException e) {
System.out.println("Cannot divide by zero.");
} catch (NullPointerException e) {
System.out.println("Null value encountered.");
}
Click to reveal answer
What will happen if an exception is thrown that does not match any catch block?
✗ Incorrect
If no catch block matches the thrown exception, the program terminates with an uncaught exception error.
Which catch block will execute if both ArithmeticException and Exception catch blocks are present and an ArithmeticException is thrown?
✗ Incorrect
Java executes the first matching catch block. Since ArithmeticException is more specific, its catch block runs.
Is it valid to have multiple catch blocks for the same exception type?
✗ Incorrect
Having multiple catch blocks for the same exception type in the same try block causes a compile-time error.
What is the correct order of catch blocks?
✗ Incorrect
Catch blocks must be ordered from most specific to most general to avoid unreachable code errors.
Can a try block have no catch blocks?
✗ Incorrect
A try block can have no catch blocks if it has a finally block to handle cleanup.
Explain how multiple catch blocks work in Java and why their order matters.
Think about how Java matches exceptions to catch blocks.
You got /3 concepts.
Write a Java try-catch example with at least two catch blocks for different exceptions and explain what each block does.
Use ArithmeticException and NullPointerException for clarity.
You got /3 concepts.