Bird
Raised Fist0
Javaprogramming~20 mins

Throwing custom exceptions in Java - Practice Problems & Coding Challenges

Choose your learning style10 modes available

Start learning this pattern below

Jump into concepts and practice - no test required

or
Recommended
Test this pattern10 questions across easy, medium, and hard to know if this pattern is strong
Challenge - 5 Problems
πŸŽ–οΈ
Custom Exception Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
❓ Predict Output
intermediate
2:00remaining
Output of custom exception throwing
What will be the output when this Java code runs?
Java
class MyException extends Exception {
    public MyException(String message) {
        super(message);
    }
}

public class Test {
    public static void check(int num) throws MyException {
        if (num < 0) {
            throw new MyException("Negative number: " + num);
        } else {
            System.out.println("Number is " + num);
        }
    }

    public static void main(String[] args) {
        try {
            check(-5);
        } catch (MyException e) {
            System.out.println("Caught: " + e.getMessage());
        }
    }
}
ACaught: Negative number: -5
BNumber is -5
CException in thread "main" MyException: Negative number: -5
DCompilation error due to missing throws declaration
Attempts:
2 left
πŸ’‘ Hint
Look at how the exception is thrown and caught in the try-catch block.
🧠 Conceptual
intermediate
1:30remaining
Understanding checked vs unchecked exceptions
Which statement correctly describes the difference between checked and unchecked exceptions in Java?
AChecked exceptions must be declared or caught; unchecked exceptions do not need to be declared or caught.
BNeither checked nor unchecked exceptions need to be declared or caught.
CBoth checked and unchecked exceptions must always be caught or declared.
DUnchecked exceptions must be declared or caught; checked exceptions do not need to be declared or caught.
Attempts:
2 left
πŸ’‘ Hint
Think about compiler requirements for exception handling.
πŸ”§ Debug
advanced
2:00remaining
Identify the error in custom exception throwing
What error will this code produce when compiled?
Java
class MyException extends Exception {
    public MyException(String message) {
        super(message);
    }
}

public class Test {
    public static void check(int num) {
        if (num < 0) {
            throw new MyException("Negative number: " + num);
        }
    }
}
ACompilation error: missing constructor in MyException
BRuntime error: MyException thrown but not caught
CCompilation error: unhandled exception type MyException
DNo error, code compiles and runs fine
Attempts:
2 left
πŸ’‘ Hint
Check if the method declares the exception it throws.
πŸ“ Syntax
advanced
1:00remaining
Correct syntax for throwing a custom exception
Which option shows the correct way to throw a custom checked exception in Java?
Athrow new MyException;
Bthrow MyException("Error occurred");
Cthrow MyException;
Dthrow new MyException("Error occurred");
Attempts:
2 left
πŸ’‘ Hint
Remember how to create new objects in Java.
πŸš€ Application
expert
3:00remaining
Result of nested custom exception handling
What will be printed when this Java program runs?
Java
class CustomException extends Exception {
    public CustomException(String msg) {
        super(msg);
    }
}

public class Main {
    public static void methodA() throws CustomException {
        throw new CustomException("Error in methodA");
    }

    public static void methodB() {
        try {
            methodA();
        } catch (CustomException e) {
            System.out.println("Caught in methodB: " + e.getMessage());
            throw new RuntimeException("Runtime in methodB");
        }
    }

    public static void main(String[] args) {
        try {
            methodB();
        } catch (RuntimeException e) {
            System.out.println("Caught in main: " + e.getMessage());
        }
    }
}
ACaught in methodB: Error in methodA
B
Caught in methodB: Error in methodA
Caught in main: Runtime in methodB
CCaught in main: Runtime in methodB
DException in thread "main" java.lang.RuntimeException: Runtime in methodB
Attempts:
2 left
πŸ’‘ Hint
Follow the flow of exceptions through the try-catch blocks.

Practice

(1/5)
1. What is the main purpose of throwing a custom exception in Java?
easy
A. To speed up the program execution.
B. To automatically fix errors in the program.
C. To create a specific error type with a clear message for better error handling.
D. To avoid writing any error handling code.

Solution

  1. Step 1: Understand what custom exceptions do

    Custom exceptions let programmers define specific error types that describe particular problems clearly.
  2. Step 2: Identify the purpose of throwing them

    Throwing a custom exception signals a specific error condition, making it easier to catch and handle that error properly.
  3. Final Answer:

    To create a specific error type with a clear message for better error handling. -> Option C
  4. Quick Check:

    Custom exceptions improve error clarity = A [OK]
Hint: Custom exceptions clarify errors for better handling [OK]
Common Mistakes:
  • Thinking exceptions fix errors automatically
  • Believing exceptions speed up code
  • Assuming exceptions remove need for error handling
2. Which of the following is the correct syntax to throw a custom exception named MyException?
easy
A. throw new MyException();
B. throw MyException();
C. throw exception MyException();
D. throw exception new MyException();

Solution

  1. Step 1: Recall Java syntax for throwing exceptions

    In Java, to throw an exception, you use the keyword throw followed by new and the exception class constructor.
  2. Step 2: Match the syntax with the options

    Only throw new MyException(); uses the correct syntax: throw new MyException();
  3. Final Answer:

    throw new MyException(); -> Option A
  4. Quick Check:

    Throw syntax = throw new Exception() [OK]
Hint: Always use 'throw new ExceptionName()' to throw exceptions [OK]
Common Mistakes:
  • Omitting the 'new' keyword
  • Adding extra keywords like 'exception'
  • Using parentheses without 'new'
3. What will be the output of the following Java code?
class MyException extends Exception {
    public MyException(String message) {
        super(message);
    }
}

public class Test {
    public static void check(int num) throws MyException {
        if (num < 0) {
            throw new MyException("Negative number not allowed");
        } else {
            System.out.println("Number is " + num);
        }
    }

    public static void main(String[] args) {
        try {
            check(-5);
        } catch (MyException e) {
            System.out.println(e.getMessage());
        }
    }
}
medium
A. Negative number not allowed
B. Compilation error
C. Number is -5
D. No output

Solution

  1. Step 1: Analyze the check method behavior

    If the input number is less than 0, it throws a MyException with message "Negative number not allowed"; otherwise, it prints the number.
  2. Step 2: Follow the main method execution

    Main calls check(-5), which triggers the exception because -5 < 0. The exception is caught and its message is printed.
  3. Final Answer:

    Negative number not allowed -> Option A
  4. Quick Check:

    Exception message printed = C [OK]
Hint: Exception message prints when thrown and caught [OK]
Common Mistakes:
  • Expecting the number to print despite exception
  • Thinking code causes compilation error
  • Ignoring exception catch block
4. 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();
    }
}
medium
A. No error; code is correct.
B. Missing 'throws' declaration in method signature.
C. Incorrect syntax for throwing exception.
D. Cannot extend Exception class.

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]
Hint: 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
5. You want to create a checked custom exception InvalidAgeException that should be thrown when age is less than 18. Which of the following code snippets correctly defines and throws this exception inside a method validateAge?
hard
A. class InvalidAgeException extends Exception { public InvalidAgeException() {} } void validateAge(int age) { if (age < 18) throw new InvalidAgeException(); }
B. class InvalidAgeException { public InvalidAgeException(String msg) { super(msg); } } void validateAge(int age) { if (age < 18) throw new InvalidAgeException("Age must be 18 or older"); }
C. class InvalidAgeException extends RuntimeException { public InvalidAgeException() {} } void validateAge(int age) { if (age < 18) throw new InvalidAgeException(); }
D. class InvalidAgeException extends Exception { public InvalidAgeException(String msg) { super(msg); } } void validateAge(int age) throws InvalidAgeException { if (age < 18) throw new InvalidAgeException("Age must be 18 or older"); }

Solution

  1. Step 1: Define a checked exception with message constructor

    class InvalidAgeException extends Exception { public InvalidAgeException(String msg) { super(msg); } } void validateAge(int age) throws InvalidAgeException { if (age < 18) throw new InvalidAgeException("Age must be 18 or older"); } correctly extends Exception and defines a constructor that accepts a message, calling super(msg).
  2. Step 2: Throw exception with message and declare it

    The method validateAge throws InvalidAgeException when age < 18 and declares it with throws InvalidAgeException.
  3. Final Answer:

    class InvalidAgeException extends Exception { public InvalidAgeException(String msg) { super(msg); } } void validateAge(int age) throws InvalidAgeException { if (age < 18) throw new InvalidAgeException("Age must be 18 or older"); } -> Option D
  4. Quick Check:

    Checked exception needs constructor, throw, and throws declaration [OK]
Hint: Checked exceptions need constructor, throw, and throws declaration [OK]
Common Mistakes:
  • Not extending Exception for checked exceptions
  • Missing throws declaration in method
  • Not calling super(message) in constructor