Java: Exception Handling

Exception handling makes programs more robust. This lesson covers Java's exception handling mechanism.

1. What is an Exception

An exception is an error that occurs during program execution.

(1) Exception Classification

TEXT 📖 Display only
Throwable
├── Error (serious errors, program cannot handle)
│   ├── OutOfMemoryError
│   └── StackOverflowError
└── Exception (exceptions, program can handle)
    ├── Checked exceptions (must handle)
    │   ├── IOException
    │   └── SQLException
    └── Unchecked exceptions (RuntimeException)
        ├── NullPointerException
        ├── ArrayIndexOutOfBoundsException
        └── NumberFormatException

2. try-catch

(1) Syntax

TEXT 📖 Display only
try {
    // Code that may throw an exception
} catch (ExceptionType variableName) {
    // Handle the exception
}

▶ Example: Basic Exception Handling

JAVA
public class TryCatchDemo {
    public static void main(String[] args) {
        try {
            int result = 10 / 0;
            System.out.println(result);
        } catch (ArithmeticException e) {
            System.out.println("Arithmetic error: " + e.getMessage());
        }
        System.out.println("Program continues");
    }
}
▶ Try it Yourself

Output:

TEXT 📖 Display only
Arithmetic error: / by zero
Program continues

(2) Multiple catch Blocks

TEXT 📖 Display only
try {
    // Code that may throw multiple exceptions
} catch (ExceptionType1 e1) {
    // Handle exception 1
} catch (ExceptionType2 e2) {
    // Handle exception 2
} catch (Exception e) {
    // Handle other exceptions
}

▶ Example: Multiple catch

JAVA
public class MultiCatch {
    public static void main(String[] args) {
        try {
            String s = "abc";
            int num = Integer.parseInt(s);
            int result = 10 / num;
        } catch (NumberFormatException e) {
            System.out.println("Number format error: " + e.getMessage());
        } catch (ArithmeticException e) {
            System.out.println("Arithmetic error: " + e.getMessage());
        } catch (Exception e) {
            System.out.println("Other error: " + e.getMessage());
        }
    }
}
▶ Try it Yourself

3. try-catch-finally

The finally block always executes, whether an exception occurs or not.

(1) Syntax

TEXT 📖 Display only
try {
    // Code that may throw an exception
} catch (ExceptionType e) {
    // Handle the exception
} finally {
    // Always executes
}

▶ Example: finally

JAVA
public class FinallyDemo {
    public static void main(String[] args) {
        try {
            System.out.println("try block");
            int result = 10 / 0;
        } catch (ArithmeticException e) {
            System.out.println("catch block");
        } finally {
            System.out.println("finally block");
        }
    }
}
▶ Try it Yourself

Output:

TEXT 📖 Display only
try block
catch block
finally block

▶ Example: Resource Release

JAVA
import java.io.*;

public class ResourceDemo {
    public static void main(String[] args) {
        FileReader reader = null;
        try {
            reader = new FileReader("test.txt");
            // Read file
        } catch (FileNotFoundException e) {
            System.out.println("File not found");
        } finally {
            // Release resource
            if (reader != null) {
                try {
                    reader.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }
}
▶ Try it Yourself

4. try-with-resources

Introduced in Java 7, automatically closes resources.

(1) Syntax

JAVA
try (ResourceType variable = new Resource()) {
    // Use resource
} catch (ExceptionType e) {
    // Handle exception
}

▶ Example: try-with-resources

JAVA
import java.io.*;

public class TryWithResources {
    public static void main(String[] args) {
        // Automatically closes resource
        try (BufferedReader reader = new BufferedReader(new FileReader("test.txt"))) {
            String line = reader.readLine();
            System.out.println(line);
        } catch (IOException e) {
            System.out.println("Read error: " + e.getMessage());
        }
        // reader automatically closed, no finally needed
    }
}
▶ Try it Yourself

5. throw and throws

(1) throw: Throw an Exception

JAVA
public static int divide(int a, int b) {
    if (b == 0) {
        throw new ArithmeticException("Cannot divide by zero");
    }
    return a / b;
}

(2) throws: Declare an Exception

TEXT 📖 Display only
public static void readFile(String path) throws FileNotFoundException {
    FileReader reader = new FileReader(path);
}

▶ Example: throw and throws

JAVA
public class ThrowDemo {
    public static int divide(int a, int b) {
        if (b == 0) {
            throw new ArithmeticException("Cannot divide by zero");
        }
        return a / b;
    }
    
    public static void validateAge(int age) {
        if (age < 0 || age > 150) {
            throw new IllegalArgumentException("Invalid age: " + age);
        }
    }
    
    public static void main(String[] args) {
        try {
            System.out.println(divide(10, 0));
        } catch (ArithmeticException e) {
            System.out.println(e.getMessage());  // Cannot divide by zero
        }
        
        try {
            validateAge(-5);
        } catch (IllegalArgumentException e) {
            System.out.println(e.getMessage());  // Invalid age: -5
        }
    }
}
▶ Try it Yourself

6. Custom Exceptions

(1) Steps

  1. Extend Exception or RuntimeException
  2. Provide constructors

▶ Example: Custom Exception

JAVA
// Custom exception class
public class InsufficientBalanceException extends Exception {
    private double balance;
    private double amount;
    
    public InsufficientBalanceException(double balance, double amount) {
        super("Insufficient balance: " + balance + ", withdrawal: " + amount);
        this.balance = balance;
        this.amount = amount;
    }
    
    public double getBalance() {
        return balance;
    }
    
    public double getAmount() {
        return amount;
    }
}

// Using custom exception
public class BankAccount {
    private double balance;
    
    public BankAccount(double balance) {
        this.balance = balance;
    }
    
    public void withdraw(double amount) throws InsufficientBalanceException {
        if (amount > balance) {
            throw new InsufficientBalanceException(balance, amount);
        }
        balance -= amount;
        System.out.println("Withdrawal successful, balance: " + balance);
    }
    
    public static void main(String[] args) {
        BankAccount account = new BankAccount(1000);
        
        try {
            account.withdraw(500);   // Withdrawal successful, balance: 500.0
            account.withdraw(800);   // Throws exception
        } catch (InsufficientBalanceException e) {
            System.out.println(e.getMessage());
            System.out.println("Balance: " + e.getBalance());
            System.out.println("Withdrawal: " + e.getAmount());
        }
    }
}
▶ Try it Yourself

7. Common Exceptions

Exception Description Cause
NullPointerException Null pointer Calling method on null object
ArrayIndexOutOfBoundsException Array index out of bounds Accessing non-existent index
NumberFormatException Number format error String to number conversion failed
ClassCastException Class cast error Downcast type mismatch
ArithmeticException Arithmetic error Dividing by zero
FileNotFoundException File not found Wrong file path
IOException IO error File read/write failed

8. Exception Handling Principles

Principle Description
Specific exceptions first Catch specific exceptions before general ones
Don't ignore exceptions At least log them
Use finally for resources Or use try-with-resources
Don't use exceptions for flow control Exceptions are for errors, not control flow

9. ❓ Frequently Asked Questions

Q What's the difference between Error and Exception?
A Error is a serious problem that the program cannot handle. Exception is a problem that the program can catch and handle.
Q What's the difference between checked and unchecked exceptions?
A Checked exceptions must be handled (try-catch or throws). Unchecked exceptions don't need to be handled.
Q When should I create custom exceptions?
A When you need to distinguish business exception types, like insufficient balance or user not found.

❓ FAQ

Q Should I use checked or unchecked exceptions?
A Use checked for recoverable conditions; unchecked for programming errors.
Q What is finally used for?
A Code that always executes regardless of exception. Used for cleanup like closing resources.
Q Can I create custom exceptions?
A Yes. Extend Exception for checked or RuntimeException for unchecked.

📖 Summary

📝 Exercises

  1. Exception handling: Write a method to read a file, handling file not found and read errors
  2. Custom exception: Define an AgeOutOfBoundsException for age validation
  3. Resource management: Use try-with-resources to implement file copying

10. Next Lesson

In the next lesson, we'll learn about Practice: OOP — applying object-oriented knowledge.

Web-Tutorial.com

Web-Tutorial Tech Team

A team of developers maintaining programming tutorials. Each tutorial is written and reviewed by developers with expertise in that field. We work to keep our content accurate and reliable — if you spot an issue, please let us know.

100%

🙏 帮我们做得更好

我们是刚上线的编程教程站,几个人的小团队,精力有限。页面虽经检查,难免还有疏漏——链接失效、排版错乱、内容有误、语言生硬……

如果您发现了,麻烦告诉我们,我们会在收到反馈后第一时间进行修复,再次感谢您的光临 🙏