Bird
Raised Fist0
Javaprogramming~20 mins

Why custom exceptions are needed in Java - Challenge Your Understanding

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 Mastery
Get all challenges correct to earn this badge!
Test your skills under time pressure!
🧠 Conceptual
intermediate
2:00remaining
Purpose of Custom Exceptions in Java
Why do developers create custom exceptions instead of using only built-in exceptions?
ATo provide more specific error information related to the application domain
BBecause Java does not have any built-in exceptions
CTo make the program run faster by avoiding built-in exceptions
DTo reduce the size of the compiled Java program
Attempts:
2 left
πŸ’‘ Hint
Think about how custom exceptions help in understanding errors better.
❓ Predict Output
intermediate
2:00remaining
Output of Custom Exception Handling
What will be the output of this Java code?
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 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());
        }
    }
}
ARuntime error: NullPointerException
BNumber is -5
CNegative number not allowed
DCompilation error due to missing exception handling
Attempts:
2 left
πŸ’‘ Hint
Look at what happens when num is less than zero.
πŸ”§ Debug
advanced
2:00remaining
Identify the Error in Custom Exception Usage
What error will this Java 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");
        }
    }
}
ARuntime error: MyException thrown but not caught
BCompilation error: unhandled exception MyException
CNo error, code compiles and runs fine
DCompilation error: MyException class not found
Attempts:
2 left
πŸ’‘ Hint
Check if the method declares the exception it throws.
πŸ“ Syntax
advanced
2:00remaining
Correct Syntax to Define a Custom Exception
Which option shows the correct way to define a custom checked exception in Java?
A
class MyException extends RuntimeException {
    public MyException(String msg) {
        super(msg);
    }
}
B
class MyException {
    public MyException(String msg) {
        super(msg);
    }
}
C
class MyException extends Throwable {
    public MyException(String msg) {
        super(msg);
    }
}
D
class MyException extends Exception {
    public MyException(String msg) {
        super(msg);
    }
}
Attempts:
2 left
πŸ’‘ Hint
Checked exceptions must extend Exception but not RuntimeException.
πŸš€ Application
expert
3:00remaining
Custom Exception Usage in Application Logic
Given this scenario: You want to signal a specific error when a user tries to withdraw more money than their account balance. Which custom exception usage is best to handle this?
ACreate a custom checked exception 'InsufficientFundsException' and throw it when withdrawal amount exceeds balance
BThrow a generic Exception with a message 'Insufficient funds' without creating a custom exception
CUse built-in NullPointerException to indicate insufficient funds
DUse RuntimeException without a custom class to signal insufficient funds
Attempts:
2 left
πŸ’‘ Hint
Think about clarity and forcing the caller to handle the error.

Practice

(1/5)
1. Why do we need custom exceptions in Java?
public class MyException extends Exception {}
easy
A. To avoid using try-catch blocks
B. To replace all built-in exceptions with new ones
C. To make the program run faster
D. To create specific error types that describe unique problems

Solution

  1. Step 1: Understand the purpose of custom exceptions

    Custom exceptions allow programmers to define errors that are specific to their application's needs, making error handling clearer.
  2. Step 2: Compare with other options

    Replacing all built-in exceptions or avoiding try-catch blocks is not the goal. Custom exceptions do not improve speed directly.
  3. Final Answer:

    To create specific error types that describe unique problems -> Option D
  4. Quick Check:

    Custom exceptions = Specific error types [OK]
Hint: Custom exceptions describe unique problems clearly [OK]
Common Mistakes:
  • Thinking custom exceptions speed up the program
  • Believing they replace all built-in exceptions
  • Assuming they remove the need for try-catch
2. Which of the following is the correct way to declare a custom checked exception in Java?
easy
A. class MyException extends RuntimeException {}
B. class MyException extends Error {}
C. class MyException extends Exception {}
D. class MyException extends Throwable {}

Solution

  1. Step 1: Identify checked exceptions

    Checked exceptions in Java must extend Exception but not RuntimeException.
  2. Step 2: Analyze each option

    Extending RuntimeException creates an unchecked exception. Extending Error is for system errors. Extending Exception creates a checked exception. Extending Throwable is too general.
  3. Final Answer:

    class MyException extends Exception {} -> Option C
  4. Quick Check:

    Checked exceptions extend Exception [OK]
Hint: Checked exceptions extend Exception class [OK]
Common Mistakes:
  • Confusing checked and unchecked exceptions
  • Extending Error instead of Exception
  • Extending Throwable directly
3. What will be the output of this code?
class MyException extends Exception {}

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

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

Solution

  1. Step 1: Understand the check method behavior

    If the number is less than 0, it throws MyException. Since -5 < 0, exception is thrown.
  2. Step 2: Analyze main method's try-catch

    The exception is caught in the catch block, which prints "Caught MyException".
  3. Final Answer:

    Caught MyException -> Option A
  4. Quick Check:

    Exception thrown and caught = "Caught MyException" [OK]
Hint: Exception thrown for negative, caught prints message [OK]
Common Mistakes:
  • Expecting negative number print instead of exception
  • Thinking code won't compile due to throws
  • Missing catch block effect
4. Identify the error in this custom exception class:
public class MyException extends Exception {
  public MyException(String message) {
    super();
  }
}
medium
A. Class should extend RuntimeException instead
B. Missing call to super(message) in constructor
C. Constructor should not have parameters
D. No error, code is correct

Solution

  1. Step 1: Check constructor call to superclass

    The constructor takes a message but calls super() without passing it, so the message is lost.
  2. Step 2: Correct usage of super constructor

    It should call super(message) to pass the error message to the Exception class.
  3. Final Answer:

    Missing call to super(message) in constructor -> Option B
  4. Quick Check:

    Pass message to super constructor [OK]
Hint: Pass message to super() in constructor [OK]
Common Mistakes:
  • Calling super() without message
  • Changing exception type unnecessarily
  • Removing constructor parameters
5. You want to create a custom exception that handles invalid user input differently from other errors. Which approach best supports this goal?
hard
A. Create a custom exception class extending Exception and catch it separately
B. Use only built-in exceptions and catch all in one block
C. Throw RuntimeException with a custom message
D. Avoid exceptions and use error codes instead

Solution

  1. Step 1: Understand the need for specific error handling

    To handle invalid input differently, a distinct exception type is needed.
  2. Step 2: Choose the best design

    Creating a custom exception extending Exception allows catching it separately and handling it clearly.
  3. Final Answer:

    Create a custom exception class extending Exception and catch it separately -> Option A
  4. Quick Check:

    Custom exception + separate catch = clear handling [OK]
Hint: Custom exception + separate catch block for clarity [OK]
Common Mistakes:
  • Using only built-in exceptions for all errors
  • Throwing RuntimeException without clarity
  • Avoiding exceptions and complicating code