跳到主要内容

Java 异常处理

异常是程序运行时发生的错误,Java 提供了异常处理机制。

异常概述

什么是异常?

异常是程序在运行过程中发生的错误情况,如除零、数组越界等。

异常分类

Throwable
├── Error(错误) - 系统级错误,无法处理
└── Exception(异常)
├── RuntimeException(运行时异常)
│ ├── NullPointerException
│ ├── ArrayIndexOutOfBoundsException
│ └── ArithmeticException
└── 其他异常
├── IOException
├── SQLException
└── ClassNotFoundException

异常处理

try-catch 语句

public class ExceptionDemo {
public static void main(String[] args) {
try {
int result = 10 / 0;
System.out.println(result);
} catch (ArithmeticException e) {
System.out.println("除数不能为零:" + e.getMessage());
}
}
}

多个 catch 语句

try {
int[] arr = {1, 2, 3};
System.out.println(arr[5]); // 数组越界
} catch (ArithmeticException e) {
System.out.println("算术异常:" + e.getMessage());
} catch (ArrayIndexOutOfBoundsException e) {
System.out.println("数组越界:" + e.getMessage());
} catch (Exception e) {
System.out.println("其他异常:" + e.getMessage());
}

try-catch-finally

try {
int result = 10 / 2;
System.out.println(result);
} catch (Exception e) {
System.out.println("异常:" + e.getMessage());
} finally {
System.out.println("finally 总是执行");
}

try-with-resources(Java 7+)

try (Scanner scanner = new Scanner(System.in)) {
String input = scanner.nextLine();
System.out.println("输入:" + input);
} catch (Exception e) {
System.out.println("异常:" + e.getMessage());
}

抛出异常

throw 语句

public static void divide(int a, int b) {
if (b == 0) {
throw new ArithmeticException("除数不能为零");
}
System.out.println(a / b);
}

throws 声明

public static void readFile(String path) throws IOException {
FileReader reader = new FileReader(path);
// 读取文件
reader.close();
}

自定义异常

// 自定义异常类
public class AgeException extends Exception {
public AgeException(String message) {
super(message);
}
}

// 使用自定义异常
public class Person {
private int age;

public void setAge(int age) throws AgeException {
if (age < 0 || age > 150) {
throw new AgeException("年龄必须在 0-150 之间");
}
this.age = age;
}
}

小结

本章我们学习了:

  1. 异常的概念和分类
  2. try-catch 语句
  3. 多个 catch 和 finally
  4. try-with-resources
  5. throw 和 throws
  6. 自定义异常

练习

  1. 编写一个方法,接受两个数相除,处理除零异常
  2. 创建一个自定义异常类
  3. 使用 try-with-resources 处理文件读取