Java throw, throws, Checked vs Unchecked and Custom Exceptions
A deposit of -20 is fine for Java but wrong for the bank, so throw rejects it. An InsufficientFundsException declines Maria's 500 with "Short by 380.0", the stack trace shows withdraw, settle and main, and the compiler refuses a checked call nobody handles.
What you will learn
- Raise an exception for your own rule with throw
- Write a custom checked exception that extends Exception
- Declare a method that can fail with throws and read its stack trace
- Tell checked from unchecked exceptions and what the compiler demands for each
Before you start
- Java exception handling: try, catch and finally
- Java inheritance: extends and super
In try, catch and finally, Java threw the exception for us. Now we raise our own, warn the callers that a method can fail, and see why Java makes you handle some exceptions but not others.
Your rule, your throw
package org.studyeasy.s03l20;
public class Ex01_Throw {
static double deposit(double balance, double amount) {
if (amount <= 0) {
// Java sees nothing wrong here, our rule does: stop and say why
throw new IllegalArgumentException("Bad amount " + amount);
}
return balance + amount;
}
public static void main(String[] args) {
System.out.println("Balance: " + deposit(100, 50));
try {
System.out.println("Balance: " + deposit(100, -20));
} catch (IllegalArgumentException e) {
System.out.println("Rejected: " + e.getMessage());
}
}
}
Balance: 150.0
Rejected: Bad amount -20.0
Depositing -20 is perfectly valid arithmetic, so Java won't complain. It's only wrong for our logic. throw new IllegalArgumentException(...) creates the exception object and throws it. Nothing after the throw runs, so return balance + amount never executes for -20, and the catch prints the message.
Make your own exception
package org.studyeasy.s03l20;
// extends Exception -> CHECKED: every caller must handle it or declare it
public class InsufficientFundsException extends Exception {
public InsufficientFundsException(String message) {
super(message); // getMessage() returns this text
}
}
A custom exception is an ordinary class that extends Exception. The constructor passes the message to super, which stores it; that's the text e.getMessage() returns later.
throws warns, throw raises
package org.studyeasy.s03l20;
public class Account {
private double balance;
public Account(double balance) {
this.balance = balance;
}
// throws: the signature tells every caller this method can fail
public void withdraw(double amount) throws InsufficientFundsException {
if (amount > balance) {
throw new InsufficientFundsException("Short by " + (amount - balance));
}
balance -= amount;
}
public double getBalance() {
return balance;
}
}
throws, with an s, goes on the signature and warns every caller that withdraw can fail. throw, without the s, goes in the body and raises one exception. When the check fails, balance -= amount never runs.
Account maria = new Account(200);
try {
maria.withdraw(80);
System.out.println("Left: " + maria.getBalance());
maria.withdraw(500);
System.out.println("Paid 500"); // skipped
} catch (InsufficientFundsException e) {
System.out.println("Declined: " + e.getMessage());
}
Left: 120.0
Declined: Short by 380.0
80 leaves 120. Then 500 is more than 120, so withdraw throws, "Paid 500" is skipped, and the message says short by 380 (500 minus 120).
Where did it come from? The stack trace
package org.studyeasy.s03l20;
public class Ex03_StackTrace {
static void settle(Account account, double amount) throws InsufficientFundsException {
account.withdraw(amount); // the exception passes through here
}
public static void main(String[] args) {
Account maria = new Account(120);
System.out.println("Settling order 41");
try {
settle(maria, 500);
} catch (InsufficientFundsException e) {
e.printStackTrace(); // the path the exception travelled, on stderr
}
}
}
Settling order 41
org.studyeasy.s03l20.InsufficientFundsException: Short by 380.0
at org.studyeasy.s03l20.Account.withdraw(Account.java:13)
at org.studyeasy.s03l20.Ex03_StackTrace.settle(Ex03_StackTrace.java:5)
at org.studyeasy.s03l20.Ex03_StackTrace.main(Ex03_StackTrace.java:12)
settle also says throws, so it passes the exception on instead of handling it. e.printStackTrace() prints the path the exception travelled to standard error (IntelliJ shows it in red): newest call first, so withdraw, then settle, then main, each with its line number. Withdraw has no catch, so its frame is removed; settle has none either, so its frame goes too; main's catch matches the type and runs.
A checked exception nobody handles
package org.studyeasy.s03l20;
public class Ex04_Unhandled {
public static void main(String[] args) {
Account maria = new Account(200);
maria.withdraw(80); // checked exception, nobody handles it
System.out.println("Left: " + maria.getBalance());
}
}
src\main\java\org\studyeasy\s03l20\Ex04_Unhandled.java:6: error: unreported exception InsufficientFundsException; must be caught or declared to be thrown
maria.withdraw(80); // checked exception, nobody handles it
^
1 error
This one doesn't even start. 80 is less than 200, so the call would never fail, but withdraw declares a checked exception and this call ignores it, so javac refuses. There are two ways out: wrap the call in try and catch, or add throws InsufficientFundsException to main. (The project excludes this file in pom.xml so the rest still builds.)
Checked or unchecked
Our exception extends Exception directly, so it's checked: javac makes every caller catch it or declare it, before the program runs. RuntimeException also sits under Exception, and everything under it is unchecked. IllegalArgumentException and ArithmeticException are two of them; they usually point to a bug in the calling code. Remove the try/catch from Ex01_Throw and it still compiles, then crashes at run time. Handling them is good practice, but Java won't force you.
Recap
| You write | Where | What it does |
|---|---|---|
throw new X(...) | method body | raises one exception |
throws X | method signature | warns every caller |
extends Exception | your class | checked: the caller must handle or declare it |
extends RuntimeException | your class | unchecked: handling is optional |
e.printStackTrace() | catch block | prints the path, newest call first |
An AI can write this syntax for you; knowing which kind you need helps you ask for the right thing. Next: closing files and connections safely with try-with-resources.
StudyEasy AI Community
Learn AI engineering, share what you build, and connect with other learners.
Free resources: lesson files, notebooks and code
Ask questions and join engineering discussions
Meet real people learning and building with AI
Related course on Udemy
FULL STACK JAVA : JAVA + JSP + SPRING BOOT AI + REACT + VIBE
Java 25, JSP, Hibernate, Spring Boot 4, REST APIs, React and Spring AI.View on Udemy ↗: FULL STACK JAVA : JAVA + JSP + SPRING BOOT AI + REACT + VIBE (paid course, opens in a new tab)Related posts
Java Exception Handling: try, catch and finally
A bill splitter crashes on a table with zero guests and table 9 never runs. try and catch keep it going, the exception travels back through the call stack to the matching catch, two catches handle 0 and "four", and finally prints the receipt either way.
Java try-with-resources and Clean Error Handling
Put the resource in the brackets after try and Java closes it when the block ends. A LogFile that implements AutoCloseable prints Closed bills.log on success and, when share(90, 0) throws, before the catch runs. Plus four habits for clean errors.
