Syntax
try {\n // risky code\n} catch (ExceptionType e) {\n // handle it\n} finally {\n // always runs\n}Examples
Basic try / catch
Catching an exception instead of letting the program crash.
try {
int result = 10 / 0;
} catch (ArithmeticException e) {
System.out.println("Error: " + e.getMessage());
}
System.out.println("Program continues running");Catching Multiple Exception Types
Handling different exceptions differently with multiple catch blocks.
public static void process(String input) {
try {
int number = Integer.parseInt(input);
int result = 100 / number;
System.out.println(result);
} catch (NumberFormatException e) {
System.out.println("Not a valid number: " + input);
} catch (ArithmeticException e) {
System.out.println("Cannot divide by zero");
}
}
process("abc"); // Not a valid number: abc
process("0"); // Cannot divide by zero
process("5"); // 20finally Block
Code in finally always executes, whether or not an exception was thrown - ideal for cleanup.
public static void readFile() {
System.out.println("Opening file...");
try {
throw new RuntimeException("File not found");
} catch (RuntimeException e) {
System.out.println("Error: " + e.getMessage());
} finally {
System.out.println("Closing file..."); // always runs
}
}
readFile();Custom Exceptions
Defining and throwing your own exception type for domain-specific error handling.
class InsufficientFundsException extends Exception {
public InsufficientFundsException(String message) {
super(message);
}
}
class BankAccount {
private double balance;
public BankAccount(double balance) { this.balance = balance; }
public void withdraw(double amount) throws InsufficientFundsException {
if (amount > balance) {
throw new InsufficientFundsException("Not enough funds for this withdrawal");
}
balance -= amount;
}
}
BankAccount account = new BankAccount(100);
try {
account.withdraw(200);
} catch (InsufficientFundsException e) {
System.out.println("Transaction failed: " + e.getMessage());
}Best practices
- Catch specific exception types rather than a broad catch (Exception e), so unrelated bugs are not accidentally silenced
- Use finally (or try-with-resources) for cleanup code that absolutely must run, like closing files or database connections
- Create custom exception classes for domain-specific errors, extending Exception (checked) or RuntimeException (unchecked) depending on whether callers should be forced to handle them
- Don't use exceptions for routine control flow when a simple if check would do - they carry real performance overhead and should signal genuinely exceptional situations
At a glance
- Purpose
- General-purpose application development
- File extension
- .java
- Runs in
- Java Virtual Machine
- Usually used with
- JDK and Java libraries
Specifications & further reading
Related Java documentation
Classes in Java are blueprints for creating objects, defining their properties (fields) and behaviors (methods). Java is a strictly object-oriented language where everything is encapsulated within classes. A class serves as a template that specifies what data an object will store and what operations it can perform.Interfaces
An interface defines a contract of methods that implementing classes must provide, without specifying how those methods work internally. Unlike a class, an interface cannot be instantiated directly - it only declares what a class can do, not how. A class uses the 'implements' keyword to fulfill an interface's contract, and a single class can implement multiple interfaces, which is Java's way of achieving a form of multiple inheritance.Abstract Classes
An abstract class is a class that cannot be instantiated directly and may contain both fully implemented methods and abstract methods (declared without a body, which subclasses must implement). Abstract classes sit between interfaces and regular classes: like an interface, they define a contract; like a regular class, they can hold state (fields) and provide shared, already-implemented behavior.Constructors
A constructor is a special method that runs automatically when an object is created with 'new', typically used to initialize the object's fields. A constructor shares its name with the class and has no return type, not even void. Java supports constructor overloading, letting a class offer multiple ways to construct an object, and constructor chaining with this(...), where one constructor calls another in the same class.