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
Throwing custom exceptions
π Scenario: Imagine you are building a simple banking application. You want to make sure that users cannot withdraw more money than they have in their account. To do this, you will create a custom exception called InsufficientFundsException and throw it when a withdrawal amount is too large.
π― Goal: Build a Java program that defines a custom exception InsufficientFundsException, uses it in a BankAccount class, and throws this exception when a withdrawal is attempted with insufficient balance.
π What You'll Learn
Create a custom exception class called InsufficientFundsException that extends Exception.
Create a BankAccount class with a balance variable.
Add a method withdraw that throws InsufficientFundsException if withdrawal amount is greater than balance.
Write code to catch the InsufficientFundsException and print a friendly message.
π‘ Why This Matters
π Real World
Custom exceptions are used in real-world applications to handle specific error cases clearly, such as banking errors, file handling problems, or invalid user input.
πΌ Career
Knowing how to create and throw custom exceptions is important for writing robust Java applications and is a common requirement in software development jobs.
Progress0 / 4 steps
1
Create the custom exception class
Create a public class called InsufficientFundsException that extends Exception. Add a constructor that takes a String message and passes it to the superclass constructor using super(message).
Java
Hint
Remember, to create a custom exception, extend the Exception class and call super(message) in the constructor.
2
Create the BankAccount class with balance
Create a public class called BankAccount. Inside it, declare a private double variable called balance. Add a constructor that takes a double parameter initialBalance and sets balance to it.
Java
Hint
Define the balance variable as private and initialize it in the constructor.
3
Add withdraw method that throws the custom exception
Inside the BankAccount class, add a public method called withdraw that takes a double parameter amount and throws InsufficientFundsException. If amount is greater than balance, throw a new InsufficientFundsException with the message "Insufficient funds for withdrawal". Otherwise, subtract amount from balance.
Java
Hint
Use throw new InsufficientFundsException("Insufficient funds for withdrawal") when the amount is too large.
4
Test withdrawal and catch the exception
Create a public class called Main with a main method. Inside main, create a BankAccount object with initial balance 100.0. Use a try-catch block to call withdraw(150.0) on the account. Catch InsufficientFundsException and print the exception message using System.out.println(e.getMessage()).
Java
Hint
Use a try-catch block to catch InsufficientFundsException and print the message.
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
Step 1: Understand what custom exceptions do
Custom exceptions let programmers define specific error types that describe particular problems clearly.
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.
Final Answer:
To create a specific error type with a clear message for better error handling. -> Option C
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
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.
Step 2: Match the syntax with the options
Only throw new MyException(); uses the correct syntax: throw new MyException();
Final Answer:
throw new MyException(); -> Option A
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
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.
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.
Final Answer:
Negative number not allowed -> Option A
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
Step 1: Check method signature for checked exceptions
Since MyException extends Exception (a checked exception), the method must declare it with throws MyException.
Step 2: Identify missing throws declaration
The method test() throws MyException but does not declare it, causing a compilation error.
Final Answer:
Missing 'throws' declaration in method signature. -> Option B
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
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).
Step 2: Throw exception with message and declare it
The method validateAge throws InvalidAgeException when age < 18 and declares it with throws InvalidAgeException.
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
Quick Check:
Checked exception needs constructor, throw, and throws declaration [OK]
Hint: Checked exceptions need constructor, throw, and throws declaration [OK]