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
Creating custom exception class
π Scenario: Imagine you are building a simple banking application. You want to handle errors when someone tries to withdraw more money than their account balance.
π― Goal: You will create a custom exception class called InsufficientFundsException and use it to show a clear error message when a withdrawal is not possible.
π What You'll Learn
Create a custom exception class named InsufficientFundsException that extends Exception.
Add a constructor to InsufficientFundsException that accepts a String message and passes it to the superclass.
Create a class called BankAccount with a private double variable balance.
Add a constructor to BankAccount that sets the initial balance.
Add a method withdraw in BankAccount that throws InsufficientFundsException if withdrawal amount is greater than balance.
Add a method getBalance to return the current balance.
Write code to test withdrawing money and catching the custom exception.
π‘ Why This Matters
π Real World
Custom exceptions help make error messages clearer and more specific in real applications like banking, shopping carts, or user input validation.
πΌ Career
Understanding how to create and use custom exceptions is important for writing robust Java programs and is a common skill required 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 super(message).
Java
Hint
Remember to extend Exception and call super(message) inside the constructor.
2
Create the BankAccount class with balance
Create a public class called BankAccount. Add a private double variable named balance. Add a constructor that takes a double initialBalance and sets balance to it.
Java
Hint
Use private double balance; and set it in the constructor.
3
Add withdraw method with exception
In the BankAccount class, add a public method withdraw that takes a double amount and throws InsufficientFundsException. If amount is greater than balance, throw new InsufficientFundsException with message "Not enough balance". Otherwise, subtract amount from balance. Also add a public method getBalance that returns the current balance.
Java
Hint
Check if amount is more than balance. If yes, throw the exception. Otherwise, reduce the balance.
4
Test withdrawing and catching exception
Create a public class Main with a main method. Inside main, create a BankAccount object with initial balance 1000. Try to withdraw 1500 inside a try block. Catch InsufficientFundsException and print its message. Also print the remaining balance after the withdrawal attempt.
Java
Hint
Use a try block to call withdraw and catch InsufficientFundsException. Print the exception message and then print the balance.
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
Step 1: Understand Java exception hierarchy
Custom exceptions must extend either Exception or RuntimeException to behave like exceptions.
Step 2: Recognize correct inheritance
Implementing an interface or naming a class Exception does not create a proper exception class.
Final Answer:
Extend the Exception or RuntimeException class -> Option A
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
Step 1: Identify correct constructor syntax
Constructors have no return type and call super(message) to pass the message to the parent Exception class.
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.
Final Answer:
public MyException(String message) { super(message); } -> Option C
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.
Final Answer:
public class InvalidDataException extends RuntimeException {
public InvalidDataException(String message) {
super(message);
}
} -> Option B