Part 06 / Topic 6 of 8
Throwing your own exception
The built-in exceptions don't know about your program's rules. An ATM amount of -200 or 250 isn't a Java-level error — -200 and 250 are both perfectly good ints — it's a business rule violation: amounts must be positive and a multiple of 100. Write your own exception class for that.
class InvalidAmountException extends RuntimeException {
InvalidAmountException(String message) {
super(message);
}
}
- Extending
RuntimeException(notException) makes it unchecked, same practical rule as the built-ins in section 5 — the usual choice for "this input was wrong" exceptions in your own code. super(message)hands the message toRuntimeException's constructor, soe.getMessage()and the stack trace both show it.- A file may have only one
publicclass, matching the file name, so a small helper exception class in a demo stays package-private (nopublickeyword).
Throw it with throw, the same keyword Java itself uses internally:
static void withdraw(int amount) {
if (amount <= 0) {
throw new InvalidAmountException("Amount must be positive, got " + amount);
}
if (amount % 100 != 0) {
throw new InvalidAmountException("Amount must be a multiple of 100, got " + amount);
}
System.out.println(" Withdrawing ₹" + amount);
}
Catch it exactly like a built-in exception:
try {
withdraw(amount);
} catch (InvalidAmountException e) {
System.out.println(" Rejected: " + e.getMessage());
}
Real output (examples/CustomExceptionDemo.java):
$ javac CustomExceptionDemo.java
$ java CustomExceptionDemo
Trying amount: 500
Withdrawing ₹500
Trying amount: -200
Rejected: Amount must be positive, got -200
Trying amount: 250
Rejected: Amount must be a multiple of 100, got 250
Trying amount: 1000
Withdrawing ₹1000
== Uncaught custom exception, for the stack trace ==
Exception in thread "main" InvalidAmountException: Amount must be positive, got -50
at CustomExceptionDemo.withdraw(CustomExceptionDemo.java:26)
at CustomExceptionDemo.main(CustomExceptionDemo.java:48)
The last line deliberately leaves withdraw(-50) uncaught — a custom exception produces a stack trace exactly like a built-in one. That trace is what the next section is about.
Full program: examples/CustomExceptionDemo.java.
Done here? The practice set for Part 6 — including the solutions — is on the part page.