Bird
Raised Fist0
Javaprogramming~10 mins

Throwing custom exceptions in Java - Step-by-Step Execution

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
Concept Flow - Throwing custom exceptions
Start
Check condition
Yes
Throw custom exception
Catch exception?
NoProgram crashes
Yes
Handle exception
End
The program checks a condition, throws a custom exception if needed, then optionally catches and handles it.
Execution Sample
Java
class MyException extends Exception {
  MyException(String msg) { super(msg); }
}

void test(int x) throws MyException {
  if (x < 0) throw new MyException("Negative not allowed");
}
Defines a custom exception and throws it when input is negative.
Execution Table
StepActionConditionResultException ThrownOutput
1Call test(5)5 < 0?FalseNoNo exception
2Call test(-3)-3 < 0?TrueYes: MyException("Negative not allowed")Exception thrown
3Catch exception?Is there a catch block?YesHandledPrint message: Negative not allowed
4Program continues--NoProgram ends normally
💡 Execution stops throwing exception if no catch; otherwise continues after handling.
Variable Tracker
VariableStartAfter test(5)After test(-3)Final
xundefined5-3-3
exceptionThrownfalsefalsetruetrue
Key Moments - 3 Insights
Why does the program stop when the exception is thrown?
Because at step 2 in the execution_table, the exception is thrown and if not caught, it stops normal flow.
What happens if there is no catch block for the custom exception?
Without a catch, the program crashes and does not continue normally.
How do you create a custom exception?
By extending Exception class and defining a constructor, as shown in the execution_sample code.
Visual Quiz - 3 Questions
Test your understanding
Look at the execution_table, what is the value of 'exceptionThrown' after step 2?
Afalse
Bundefined
Ctrue
Dnull
💡 Hint
Check the variable_tracker row for 'exceptionThrown' after test(-3)
At which step does the program handle the exception?
AStep 2
BStep 3
CStep 1
DStep 4
💡 Hint
Look at the 'Exception Thrown' and 'Output' columns in execution_table
If the condition 'x < 0' was changed to 'x <= 0', what would happen at step 1 when x=0?
AException thrown
BNo exception
CProgram crashes immediately
DException caught at step 3
💡 Hint
Refer to the condition column in execution_table and how it controls throwing exception
Concept Snapshot
Throwing custom exceptions in Java:
- Create a class extending Exception
- Use 'throw new MyException(message)' to throw
- Declare 'throws MyException' in method signature
- Catch with try-catch to handle
- If uncaught, program stops with error
Full Transcript
This visual trace shows how Java throws and handles custom exceptions. First, a method checks a condition. If the condition is true, it throws a custom exception object. The program then looks for a catch block to handle this exception. If found, it runs the catch code and continues. If not, the program stops with an error. Variables like 'x' and 'exceptionThrown' track the input and whether an exception occurred. This helps beginners see step-by-step how exceptions interrupt normal flow and how to manage them.

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