Your own exception classes
30 min · Beginner
Need help? Ask a tutor on WhatsApp (opens in a new tab)A custom exception is your own exception class, made with inheritance: class InsufficientBalanceException extends Exception. It names the exact problem in your program, so the code that catches it knows what went wrong.
Why make your own exception?
A custom exception is an exception class you write yourself, named after one problem in your app. In throw and throws (opens in a new tab) you threw built-in ones like IllegalArgumentException, but that type says little: many different problems share it.
A bank app has its own problems: not enough balance, a wrong PIN, a daily limit crossed. One class for each makes the code read like the bank's rules, and catch (InsufficientBalanceException e) handles exactly that case.
Writing one: extend Exception
An exception class is a normal class that extends Exception. Give it a constructor that takes a message and passes it up with super(message): that is the whole class.
Example 1 · Your first custom exception
class InsufficientBalanceException extends Exception { InsufficientBalanceException(String message) { super(message); }}
class Account { private int balance;
Account(int balance) { this.balance = balance; }
void withdraw(int amount) throws InsufficientBalanceException { if (amount > balance) { throw new InsufficientBalanceException("Need Rs. " + amount + ", have Rs. " + balance); } balance = balance - amount; System.out.println("Withdrew Rs. " + amount); }}
public class CustomDemo { public static void main(String[] args) { Account a = new Account(1000); try { a.withdraw(400); a.withdraw(800); System.out.println("Done"); } catch (InsufficientBalanceException e) { System.out.println("Failed: " + e.getMessage()); } }}Withdrew Rs. 400 Failed: Need Rs. 800, have Rs. 600
What this code does
- The class is three lines of real code:
extends Exceptionand a constructor that callssuper(message). - The second
withdrawthrows, soDoneis skipped.getMessage(), inherited fromException, returns the message.
End the name with Exception, like InvalidPinException, so every reader knows what the class is. You never wrote getMessage(): it is inherited, which is inheritance doing the work for you.
Checked or unchecked?
Your parent class decides the kind. extends Exception makes a checked exception: every method that can throw it must say throws, and every caller must catch it or declare it too.
Example 2 · Mistake: a checked exception that is not handled
class InsufficientBalanceException extends Exception { InsufficientBalanceException(String message) { super(message); }}
class Account { private int balance;
Account(int balance) { this.balance = balance; }
void withdraw(int amount) throws InsufficientBalanceException { if (amount > balance) { throw new InsufficientBalanceException("Need Rs. " + amount + ", have Rs. " + balance); } balance = balance - amount; System.out.println("Withdrew Rs. " + amount); }}
public class UnhandledDemo { public static void main(String[] args) { Account a = new Account(1000); a.withdraw(400); }}UnhandledDemo.java:26: error: unreported exception InsufficientBalanceException; must be caught or declared to be thrown
a.withdraw(400);
^
1 errorWhat this code does
InsufficientBalanceExceptionextendsException, so it is checked.mainneither catches it nor declares it.- The fix: put the call in
try/catch, or addthrows InsufficientBalanceExceptiontomain.
Example 3 · An unchecked custom exception
class InvalidMarksException extends RuntimeException { InvalidMarksException(String message) { super(message); }}
class Student { private int marks;
void setMarks(int marks) { if (marks < 0 || marks > 100) { throw new InvalidMarksException("Marks must be 0 to 100, got " + marks); } this.marks = marks; System.out.println("Marks set: " + marks); }}
public class UncheckedDemo { public static void main(String[] args) { Student s = new Student(); s.setMarks(88); s.setMarks(150); System.out.println("Not reached"); }}Marks set: 88 Exception in thread "main" InvalidMarksException: Marks must be 0 to 100, got 150 at Student.setMarks(UncheckedDemo.java:12) at UncheckedDemo.main(UncheckedDemo.java:23)
What this code does
- It extends
RuntimeException, sosetMarksneeds nothrows, andmaincompiles without acatch. - Nobody catches it, so the program stops. The report shows your class name and your message.
extends RuntimeException makes an unchecked one: no throws and no forced catch, as in throw and throws (opens in a new tab). Choose checked for a problem the caller should expect and handle, like low balance. Choose unchecked for a bug or a value that should never come in, like marks of 150.
Throwing and catching
An ATM can fail for a wrong PIN or for low balance. Throw each problem as its own class, throw new InvalidPinException("Wrong PIN"), and give each one its own catch block.
Example 4 · An ATM with two custom exceptions
class InvalidPinException extends Exception { InvalidPinException(String message) { super(message); }}
class InsufficientBalanceException extends Exception { InsufficientBalanceException(String message) { super(message); }}
class Atm { private int pin = 4321; private int balance = 5000;
void withdraw(int enteredPin, int amount) throws InvalidPinException, InsufficientBalanceException { if (enteredPin != pin) throw new InvalidPinException("Wrong PIN"); if (amount > balance) throw new InsufficientBalanceException("Balance is Rs. " + balance); balance = balance - amount; System.out.println("Collect Rs. " + amount); }}
public class AtmDemo { public static void main(String[] args) { Atm atm = new Atm(); int[][] tries = {{1111, 500}, {4321, 9000}, {4321, 2000}}; for (int[] t : tries) { try { atm.withdraw(t[0], t[1]); } catch (InvalidPinException e) { System.out.println("PIN error: " + e.getMessage()); } catch (InsufficientBalanceException e) { System.out.println("Balance error: " + e.getMessage()); } } }}PIN error: Wrong PIN Balance error: Balance is Rs. 5000 Collect Rs. 2000
What this code does
- Each problem has its own class, so each
catchblock handles exactly one case. - The
throwsline lists both checked exceptions; the loop keeps going after each caught one.
The try sits inside the loop, so one failed withdrawal does not stop the next one. A caller that does not care which problem happened can catch both with one parent type, shown next.
A family of exceptions
A UPI screen wants one catch for every bank error. Make BankException extends Exception and let each problem extend it: a low-balance exception is a bank exception, so catch (BankException e) catches them all.
Example 5 · One catch for the whole family
class BankException extends Exception { BankException(String message) { super(message); }}
class InsufficientBalanceException extends BankException { InsufficientBalanceException(String message) { super(message); }}
class DailyLimitException extends BankException { DailyLimitException(String message) { super(message); }}
class Upi { private int balance = 3000;
void pay(int amount) throws BankException { if (amount > 2000) throw new DailyLimitException("Limit is Rs. 2000"); if (amount > balance) throw new InsufficientBalanceException("Low balance"); balance = balance - amount; System.out.println("Paid Rs. " + amount); }}
public class FamilyDemo { public static void main(String[] args) { Upi u = new Upi(); int[] payments = {1500, 2500, 1800}; for (int p : payments) { try { u.pay(p); } catch (BankException e) { System.out.println("Payment failed: " + e.getMessage()); } } }}Paid Rs. 1500 Payment failed: Limit is Rs. 2000 Payment failed: Low balance
What this code does
- Both children pass the message up through
BankExceptiontoException:super(message)at each level. - Each child is a
BankException, so onecatch (BankException e)and onethrows BankExceptioncover both.
Another screen can still catch one child first and the parent after it. Child catch blocks go before the parent's, as in Multiple catch blocks (opens in a new tab); the other order does not compile.
Predict the output
Predict which catch runs
Read the code and pick what it prints.
Round 1 of 3
getMessage() should print "Only 3 left". What does it print?
Next step
Check your understanding
11 quick questions