In the previous chapter, we learned how to catch exceptions using try, catch, and finally, and we had a quick first look at throw and throws. In this chapter, we will go deeper and look at the other side of exception handling: how to create and report problems ourselves.
Think of a bank. When you try to withdraw more money than you have, the bank doesn't just quietly give you less money. It refuses the request and tells you exactly why: "Insufficient funds". Our methods should do the same. When they receive invalid input or cannot do their job, they should throw an exception with a clear message, and let the caller decide what to do.
We will cover:
The exception class hierarchy
throw: how to throw an exceptionHow exceptions travel up the call stack
throws: declaring checked exceptionsCreating your own custom exceptions
Exception chaining and best practices
The Exception Hierarchy
Every exception in Java is an object, and all exception classes come from one parent class called Throwable:
Throwable
┌──────┴───────┐
Error Exception ← checked (except RuntimeException branch)
│ ┌─────┴──────────────┐
OutOfMemoryError IOException RuntimeException ← unchecked
StackOverflowError ┌──────┼────────────────────┐
ArithmeticException NullPointerException IllegalArgumentException
│
NumberFormatExceptionError: serious problems in the JVM itself, such as running out of memory. Programs usually should not try to catch these.
Checked exceptions:
Exceptionand its subclasses, exceptRuntimeExceptionand its subclasses. The compiler forces you to handle or declare them.Unchecked exceptions:
RuntimeExceptionand its subclasses. They usually indicate programming mistakes or invalid arguments, and the compiler does not force you to handle them.
This hierarchy matters for two reasons. A catch block for a parent class also catches all its subclasses (that is why catch (Exception e) catches almost everything), and the checked/unchecked difference decides whether you need throws.
The throw Keyword
throw is a statement that hands an exception object to Java, immediately stopping the current method.
The syntax is:
throw new ExceptionType("message");A few important points:
We throw an object, so we usually create it with
new.Only objects of
Throwableor its subclasses can be thrown.throw new String("oops")giveserror: incompatible types: String cannot be converted to Throwable.The statement after
throwin the same block can never run, so Java reportserror: unreachable statementif you write one.
Let's see what happens when a thrown exception is not caught:
class Main {
static void setAge(int age) {
if (age < 0) {
throw new IllegalArgumentException("Age cannot be negative: " + age);
}
System.out.println("Age set to " + age);
}
public static void main(String[] args) {
setAge(21);
setAge(-5);
System.out.println("This line never runs");
}
}Output:
Age set to 21
Exception in thread "main" java.lang.IllegalArgumentException: Age cannot be negative: -5
at Main.setAge(Main.java:5)
at Main.main(Main.java:12)The first call works. The second call throws, nobody catches the exception, and the program stops. Java prints the exception type, our message, and a stack trace. Read the stack trace from top to bottom: the exception happened in setAge at line 5, which was called from main at line 12. This is the most useful information you have when debugging.
Which exception should you throw? For unchecked problems, Java already has good built-in ones:
Exception | Throw it when |
|---|---|
| A method receives an invalid argument (negative age, empty name) |
| The object is in the wrong state for the operation (withdrawing from a closed account) |
| A required argument is |
| The operation is not supported by this object |
How Exceptions Travel Up the Call Stack
When a method throws an exception and doesn't catch it, the method ends immediately and the exception is passed to the method that called it. This continues up the chain of calls until some method catches it. If nobody does, the program stops, just like above. This is called exception propagation.
class Main {
static void checkQuantity(int quantity) {
System.out.println(" checkQuantity(" + quantity + ") started");
if (quantity <= 0) {
throw new IllegalArgumentException("Quantity must be positive");
}
System.out.println(" checkQuantity finished");
}
static void placeOrder(int quantity) {
System.out.println(" placeOrder started");
checkQuantity(quantity);
System.out.println(" placeOrder finished"); // skipped if an exception occurs
}
public static void main(String[] args) {
System.out.println("main started");
try {
placeOrder(0);
} catch (IllegalArgumentException e) {
System.out.println("Caught in main: " + e.getMessage());
}
System.out.println("main finished");
}
}Output:
main started
placeOrder started
checkQuantity(0) started
Caught in main: Quantity must be positive
main finishedNotice that "checkQuantity finished" and "placeOrder finished" were never printed. The exception jumped straight out of both methods:
main() ← catches it here, then continues normally
└─ placeOrder() ← no catch: ends immediately, passes it up
└─ checkQuantity() ← throw happens hereThis is powerful: the method that detects the problem (checkQuantity) doesn't need to know how to handle it. The method that knows what to do (main, which could show a message to the user) catches it.
The throws Keyword
For unchecked exceptions, propagation happens automatically. But for checked exceptions, Java has a strict rule:
A checked exception must either be caught with try-catch, or declared in the method signature with throws.
If we throw a checked exception without doing either:
static void loadConfig(String fileName) {
throw new Exception("Unsupported config file: " + fileName);
}the code doesn't compile:
error: unreported exception Exception; must be caught or declared to be thrownAdding throws Exception fixes it, and passes the responsibility to every caller:
class Main {
// throws tells callers: "you must deal with this checked exception"
static void loadConfig(String fileName) throws Exception {
if (!fileName.endsWith(".properties")) {
throw new Exception("Unsupported config file: " + fileName);
}
System.out.println("Loaded " + fileName);
}
// This method doesn't handle it either, so it also declares throws
static void startApp(String fileName) throws Exception {
loadConfig(fileName);
System.out.println("App started");
}
public static void main(String[] args) {
try {
startApp("app.properties");
startApp("app.txt");
} catch (Exception e) {
System.out.println("Startup failed: " + e.getMessage());
}
}
}Output:
Loaded app.properties
App started
Startup failed: Unsupported config file: app.txtstartApp() calls loadConfig() but doesn't handle the exception, so it must also declare throws Exception. Finally, main() catches it. If main() called startApp() without a try-catch, we would get the same "unreported exception" error there.
A method can declare several exceptions, separated by commas:
void importData(String path) throws IOException, InterruptedException {
// ...
}You can add unchecked exceptions to throws too, as documentation, but the compiler doesn't require it.
throw vs throws
|
|
|---|---|
A statement that actually throws an exception | Part of a method signature that declares possible exceptions |
Used inside a method body | Used after the method's parameter list |
Followed by one exception object: | Followed by one or more exception class names: |
Stops the method immediately | Doesn't do anything at runtime by itself; it informs the compiler and callers |
Creating a Custom Checked Exception
Built-in exceptions are general. In real applications, it is often clearer to create exceptions that describe your problem, such as InsufficientFundsException or StudentNotFoundException. A custom exception is just a class that extends an existing exception class.
To create a checked exception, extend Exception:
// A custom CHECKED exception: extends Exception
class InsufficientFundsException extends Exception {
private final double shortBy;
InsufficientFundsException(String message, double shortBy) {
super(message); // pass the message to Exception
this.shortBy = shortBy;
}
double getShortBy() {
return shortBy;
}
}
class BankAccount {
private double balance;
BankAccount(double balance) {
this.balance = balance;
}
void withdraw(double amount) throws InsufficientFundsException {
if (amount > balance) {
throw new InsufficientFundsException(
"Cannot withdraw " + amount + ", balance is " + balance,
amount - balance);
}
balance -= amount;
System.out.println("Withdrawn: " + amount + ", remaining: " + balance);
}
}
class Main {
public static void main(String[] args) {
BankAccount account = new BankAccount(5000);
try {
account.withdraw(2000);
account.withdraw(4000);
account.withdraw(500); // never reached
} catch (InsufficientFundsException e) {
System.out.println("Error: " + e.getMessage());
System.out.println("You are short by Rs. " + e.getShortBy());
}
}
}Output:
Withdrawn: 2000.0, remaining: 3000.0
Error: Cannot withdraw 4000.0, balance is 3000.0
You are short by Rs. 1000.0Key points:
super(message)passes the message to theExceptionconstructor, sogetMessage()works automatically.A custom exception is a normal class, so it can carry extra data. Here,
shortBytells the caller exactly how much money was missing.Because it is checked,
withdraw()must declarethrows InsufficientFundsException, and the caller is forced to think about it.By convention, exception class names end with
Exception.
Creating a Custom Unchecked Exception
To create an unchecked exception, extend RuntimeException. No throws clause is required:
// A custom UNCHECKED exception: extends RuntimeException
class InvalidMarksException extends RuntimeException {
InvalidMarksException(String message) {
super(message);
}
}
class Main {
// No throws clause needed for unchecked exceptions
static String grade(int marks) {
if (marks < 0 || marks > 100) {
throw new InvalidMarksException("Marks must be 0-100, got " + marks);
}
if (marks >= 90) return "A";
if (marks >= 75) return "B";
if (marks >= 40) return "C";
return "F";
}
public static void main(String[] args) {
int[] allMarks = {95, 82, 120, 30};
for (int marks : allMarks) {
try {
System.out.println(marks + " : " + grade(marks));
} catch (InvalidMarksException e) {
System.out.println("Skipped: " + e.getMessage());
}
}
}
}Output:
95 : A
82 : B
Skipped: Marks must be 0-100, got 120
30 : FBecause the try-catch is inside the loop, one bad value doesn't stop the remaining values from being processed.
Checked or unchecked: which should you choose?
Choose checked (extend
Exception) when the problem is expected and the caller can reasonably recover from it, such as insufficient balance, a missing file, or a failed network call.Choose unchecked (extend
RuntimeException) when the problem is caused by a bug or invalid input that the caller should have prevented, such as out-of-range marks or anullargument.
Many modern Java libraries prefer unchecked exceptions because they don't force throws clauses through every method. Both approaches are valid; just be consistent.
Exception Chaining
Sometimes we catch a low-level exception and want to throw a more meaningful one. We should not lose the original exception, because it contains the real reason for the failure. Java lets us attach it as the cause:
class InvalidInputException extends Exception {
InvalidInputException(String message, Throwable cause) {
super(message, cause); // keep the original exception as the cause
}
}
class Main {
static int parseAge(String text) throws InvalidInputException {
try {
return Integer.parseInt(text);
} catch (NumberFormatException e) {
throw new InvalidInputException("Age must be a number", e);
}
}
public static void main(String[] args) {
try {
System.out.println("Age: " + parseAge("25"));
System.out.println("Age: " + parseAge("twenty"));
} catch (InvalidInputException e) {
System.out.println("Message: " + e.getMessage());
System.out.println("Cause: " + e.getCause());
}
}
}Output:
Age: 25
Message: Age must be a number
Cause: java.lang.NumberFormatException: For input string: "twenty"The Exception(String message, Throwable cause) constructor stores the original exception, and getCause() gets it back. If this exception were printed as a stack trace, Java would show both, with a Caused by: section for the original. This is called exception chaining, and it makes debugging much easier.
Catching Multiple Exceptions in One Block
When different exceptions need the same handling, we can catch them together using | (available since Java 7):
class Main {
static void process(String input, int index) {
try {
int number = Integer.parseInt(input);
int[] data = {10, 20, 30};
System.out.println(data[index] / number);
} catch (NumberFormatException | ArrayIndexOutOfBoundsException e) {
System.out.println("Bad input: " + e.getClass().getSimpleName());
} catch (ArithmeticException e) {
System.out.println("Math error: " + e.getMessage());
}
}
public static void main(String[] args) {
process("5", 1);
process("abc", 1);
process("5", 7);
process("0", 1);
}
}Output:
4
Bad input: NumberFormatException
Bad input: ArrayIndexOutOfBoundsException
Math error: / by zeroThe exception types in a multi-catch cannot be parent and child of each other. For example, catch (NumberFormatException | IllegalArgumentException e) does not compile, because NumberFormatException is already a subclass of IllegalArgumentException.
Exceptions and Method Overriding
There is one rule connecting this chapter to Method Overriding: an overriding method cannot throw a new or broader checked exception than the method it overrides.
import java.io.IOException;
class Parent {
void save() throws IOException { }
}
class Child extends Parent {
@Override
void save() throws Exception { } // Error: Exception is broader than IOException
}error: save() in Child cannot override save() in Parent
overridden method does not throw ExceptionThe reason: code that calls save() on a Parent reference only prepared for IOException. If a child could throw something broader, that code would break. The overriding method can throw the same exception, a subclass of it (like FileNotFoundException), fewer exceptions, or any unchecked exception.
Best Practices
Throw early, catch where you can handle it. Validate inputs at the start of a method, and catch exceptions at the level that can do something useful (show a message, retry, use a default).
Write clear messages.
"Marks must be 0-100, got 120"is far more helpful than"Invalid". Include the bad value.Be specific. Throw and catch specific types like
InsufficientFundsExceptioninstead of plainException.Never swallow exceptions. An empty
catch (Exception e) { }hides bugs. At least log or print the problem.Keep the cause. When converting one exception into another, pass the original as the cause.
Don't use exceptions for normal flow. If something is a normal outcome (like a search finding nothing), return a value instead of throwing.
Interview Tips
Difference between throw and throws?
throwactually throws one exception object inside a method;throwsdeclares in the signature which checked exceptions a method may throw.Difference between checked and unchecked? Checked exceptions (subclasses of
Exceptionbut notRuntimeException) must be caught or declared; unchecked ones (subclasses ofRuntimeException) need not be.How do you create a custom exception? Extend
Exception(checked) orRuntimeException(unchecked) and callsuper(message)in the constructor.Is Error checked or unchecked? Unchecked. The compiler doesn't force you to handle
Erroror its subclasses.
The Main Idea
Exception handling has two sides. In the previous chapter we learned to catch problems; in this chapter we learned to report them.
Use throw to report a problem, throws to declare checked exceptions, and custom exceptions to describe problems in the language of your own application.
Well-chosen exceptions with clear messages turn confusing crashes into problems that are easy to understand and fix.