# Java Exception Handling Best Practices
Proper exception handling is crucial for robust Java applications. Here’s how to handle exceptions effectively:
import java.io.FileReader;import java.io.IOException;
public class ExceptionExample { public void readFile(String fileName) { try (FileReader reader = new FileReader(fileName)) { // File processing logic int character; while ((character = reader.read()) != -1) { System.out.print((char) character); } } catch (IOException e) { System.err.println("Error reading file: " + e.getMessage()); // Log the exception properly in real applications } }}
Creating custom exceptions for better error handling:
public class InsufficientFundsException extends Exception { private final double amount; private final double balance;
public InsufficientFundsException(double amount, double balance) { super(String.format("Insufficient funds: tried to withdraw %.2f, balance is %.2f", amount, balance)); this.amount = amount; this.balance = balance; }
public double getAmount() { return amount; } public double getBalance() { return balance; }}
public class BankAccount { private double balance;
public void withdraw(double amount) throws InsufficientFundsException { if (amount > balance) { throw new InsufficientFundsException(amount, balance); } balance -= amount; }}
Best practices include using try-with-resources for automatic resource management and creating specific exception types for different error scenarios.
javac *.java && java ExceptionExample