Bird
0
0

Identify the error in the following code snippet that throws a custom exception:

medium📝 Debug Q14 of 15
Java - Custom Exceptions
Identify the error in the following code snippet that throws a custom exception:
class MyException extends Exception {}

public class Demo {
    public static void test() {
        throw new MyException();
    }
}
ANo error; code is correct.
BMissing 'throws' declaration in method signature.
CIncorrect syntax for throwing exception.
DCannot extend Exception class.
Step-by-Step Solution
Solution:
  1. Step 1: Check method signature for checked exceptions

    Since MyException extends Exception (a checked exception), the method must declare it with throws MyException.
  2. Step 2: Identify missing throws declaration

    The method test() throws MyException but does not declare it, causing a compilation error.
  3. Final Answer:

    Missing 'throws' declaration in method signature. -> Option B
  4. Quick Check:

    Checked exceptions require 'throws' declaration [OK]
Quick Trick: Add 'throws ExceptionName' when throwing checked exceptions [OK]
Common Mistakes:
  • Forgetting 'throws' in method signature
  • Thinking all exceptions are unchecked
  • Assuming extending Exception is invalid

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More Java Quizzes