Bird
Raised Fist0
Javaprogramming~20 mins

Creating custom exception class in Java - Practice Exercises

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 message
What is the output of this Java program that uses a custom exception class?
Java
class MyException extends Exception {
    public MyException(String message) {
        super(message);
    }
}

public class Test {
    public static void main(String[] args) {
        try {
            throw new MyException("Custom error occurred");
        } catch (MyException e) {
            System.out.println(e.getMessage());
        }
    }
}
ACustom error occurred
BMyException: Custom error occurred
CCompilation error
DException in thread "main" MyException: Custom error occurred
Attempts:
2 left
πŸ’‘ Hint
Look at what getMessage() returns from the Exception class.
❓ Predict Output
intermediate
2:00remaining
Value of variable after catching custom exception
What is the value of variable 'result' after running this code?
Java
class MyException extends Exception {}

public class Test {
    public static int testMethod() throws MyException {
        throw new MyException();
    }

    public static void main(String[] args) {
        int result = 0;
        try {
            result = testMethod();
        } catch (MyException e) {
            result = -1;
        }
        System.out.println(result);
    }
}
A0
B-1
CCompilation error
DException in thread "main" java.lang.MyException
Attempts:
2 left
πŸ’‘ Hint
Consider what happens when the exception is thrown and caught.
πŸ“ Syntax
advanced
2:00remaining
Identify syntax error in custom exception class
Which option contains a syntax error in defining a custom exception class?
A
public class MyException extends Exception {
    public MyException() {}
}
B
public class MyException extends Exception {
    public MyException() {
        super();
    }
}
C
public class MyException extends Exception {
    public MyException(String message) {
        super(message);
    }
}
D
public class MyException extends Exception {
    public MyException(String message) {
        this.message = message;
    }
}
Attempts:
2 left
πŸ’‘ Hint
Check how the superclass Exception stores the message.
🧠 Conceptual
advanced
2:00remaining
Purpose of creating a custom exception class
Why would a developer create a custom exception class instead of using existing Java exceptions?
ATo avoid using try-catch blocks in the code
BTo automatically fix errors during runtime
CTo provide more specific error information related to the application domain
DTo improve the performance of exception handling
Attempts:
2 left
πŸ’‘ Hint
Think about how exceptions help communicate problems.
πŸ”§ Debug
expert
2:00remaining
Why does this custom exception code fail to compile?
This code tries to define a custom checked exception but fails to compile. What is the cause?
Java
class MyException extends Exception {
    public MyException() {
        System.out.println("Error");
    }
}

public class Test {
    public static void main(String[] args) {
        throw new MyException();
    }
}
AYou cannot throw checked exceptions without declaring them in method signature
BMyException constructor does not call super(), causing a compile error
CThe catch block must catch Exception, not MyException
DSystem.out.println cannot be used inside exception constructors
Attempts:
2 left
πŸ’‘ Hint
Check the method main's throws declaration and checked exceptions rules.

Practice

(1/5)
1. What is the correct way to start creating a custom exception class in Java?
easy
A. Extend the Exception or RuntimeException class
B. Implement the Exception interface
C. Create a class with the same name as Exception
D. Use the throw keyword in the class declaration

Solution

  1. Step 1: Understand Java exception hierarchy

    Custom exceptions must extend either Exception or RuntimeException to behave like exceptions.
  2. Step 2: Recognize correct inheritance

    Implementing an interface or naming a class Exception does not create a proper exception class.
  3. Final Answer:

    Extend the Exception or RuntimeException class -> Option A
  4. Quick Check:

    Custom exception = extends Exception [OK]
Hint: Always extend Exception or RuntimeException for custom exceptions [OK]
Common Mistakes:
  • Trying to implement Exception as an interface
  • Naming class Exception instead of extending it
  • Using throw keyword in class declaration
2. Which of the following is the correct constructor for a custom exception class named MyException?
easy
A. public MyException() { this.message = message; }
B. public void MyException(String message) { super(message); }
C. public MyException(String message) { super(message); }
D. public MyException(String message) { print(message); }

Solution

  1. Step 1: Identify correct constructor syntax

    Constructors have no return type and call super(message) to pass the message to the parent Exception class.
  2. Step 2: Check each option

    public MyException(String message) { super(message); } correctly defines a constructor calling super(message). public MyException() { this.message = message; } incorrectly assigns message without declaration. public void MyException(String message) { super(message); } has a void return type, so it's not a constructor. public MyException(String message) { print(message); } calls a non-existent method print.
  3. Final Answer:

    public MyException(String message) { super(message); } -> Option C
  4. Quick Check:

    Constructor calls super(message) = public MyException(String message) { super(message); } [OK]
Hint: Constructor must call super(message) without return type [OK]
Common Mistakes:
  • Adding void return type to constructor
  • Not calling super(message) in constructor
  • Trying to assign message directly without declaration
3. What will be the output of this code?
class MyException extends Exception {
    public MyException(String message) {
        super(message);
    }
}

public class Test {
    public static void main(String[] args) {
        try {
            throw new MyException("Error occurred");
        } catch (MyException e) {
            System.out.println(e.getMessage());
        }
    }
}
medium
A. Error occurred
B. MyException
C. Compilation error
D. No output

Solution

  1. Step 1: Understand exception throwing and catching

    The code throws a MyException with message "Error occurred" and catches it immediately.
  2. Step 2: Check output from getMessage()

    The catch block prints e.getMessage(), which returns the message passed to the exception.
  3. Final Answer:

    Error occurred -> Option A
  4. Quick Check:

    Exception message printed = Error occurred [OK]
Hint: getMessage() prints the exception message passed in constructor [OK]
Common Mistakes:
  • Expecting class name instead of message
  • Thinking code won't compile due to custom exception
  • Missing try-catch block causing runtime error
4. Identify the error in this custom exception class:
public class MyException extends Exception {
    public void MyException(String message) {
        super(message);
    }
}
medium
A. super(message) cannot be called in this class
B. Missing import statement for Exception
C. Class must implement Serializable interface
D. Constructor has a void return type, so it's a method, not a constructor

Solution

  1. Step 1: Check constructor syntax

    Constructors must not have a return type. Here, void makes it a method, not a constructor.
  2. Step 2: Understand consequences

    Without a proper constructor, the class uses default constructor which does not call super(message), causing errors when throwing with message.
  3. Final Answer:

    Constructor has a void return type, so it's a method, not a constructor -> Option D
  4. Quick Check:

    Constructor no return type = Constructor has a void return type, so it's a method, not a constructor [OK]
Hint: Constructors never have a return type, not even void [OK]
Common Mistakes:
  • Adding void return type to constructor
  • Assuming import Exception is needed
  • Thinking super() cannot be called in subclass
5. You want to create a custom unchecked exception named InvalidDataException. Which is the correct way to define it?
hard
A. public class InvalidDataException implements RuntimeException { public InvalidDataException(String message) { super(message); } }
B. public class InvalidDataException extends RuntimeException { public InvalidDataException(String message) { super(message); } }
C. public class InvalidDataException extends Exception { public InvalidDataException(String message) { super(message); } }
D. public class InvalidDataException extends Throwable { public InvalidDataException(String message) { super(message); } }

Solution

  1. Step 1: Understand checked vs unchecked exceptions

    Unchecked exceptions extend RuntimeException, checked exceptions extend Exception.
  2. Step 2: Analyze each option

    public class InvalidDataException extends RuntimeException { public InvalidDataException(String message) { super(message); } } correctly extends RuntimeException with proper constructor. public class InvalidDataException extends Exception { public InvalidDataException(String message) { super(message); } } creates a checked exception. public class InvalidDataException implements RuntimeException { public InvalidDataException(String message) { super(message); } } tries to implement an exception class, which is invalid. public class InvalidDataException extends Throwable { public InvalidDataException(String message) { super(message); } } extends Throwable directly, which is not recommended for custom exceptions.
  3. Final Answer:

    public class InvalidDataException extends RuntimeException { public InvalidDataException(String message) { super(message); } } -> Option B
  4. Quick Check:

    Unchecked exception = extends RuntimeException [OK]
Hint: Unchecked exceptions extend RuntimeException, not Exception [OK]
Common Mistakes:
  • Extending Exception for unchecked exceptions
  • Trying to implement exception classes
  • Extending Throwable directly