java 如何抛出异常
抛出异常的方法
在 Java 中,可以通过 throw 关键字手动抛出异常。异常可以是 Java 内置的异常类(如 IllegalArgumentException、NullPointerException),也可以是自定义的异常类。
throw new ExceptionType("Error message");
内置异常示例
以下代码演示如何抛出一个内置异常(IllegalArgumentException):
public void validateAge(int age) {
if (age < 0) {
throw new IllegalArgumentException("Age cannot be negative");
}
}
自定义异常示例
如果需要抛出自定义异常,需先定义一个继承自 Exception 或 RuntimeException 的类:
class CustomException extends Exception {
public CustomException(String message) {
super(message);
}
}
随后在代码中抛出:
public void processInput(String input) throws CustomException {
if (input == null) {
throw new CustomException("Input cannot be null");
}
}
方法声明异常
如果方法内部抛出受检异常(checked exception),必须在方法签名中使用 throws 声明:
public void readFile(String path) throws IOException {
if (!new File(path).exists()) {
throw new IOException("File not found");
}
}
运行时异常
非受检异常(unchecked exception,如 RuntimeException 及其子类)无需在方法签名中声明:

public void divide(int a, int b) {
if (b == 0) {
throw new ArithmeticException("Division by zero");
}
System.out.println(a / b);
}
最佳实践
- 优先使用标准异常(如
IllegalArgumentException、IllegalStateException)而非自定义异常。 - 受检异常用于可恢复情况,非受检异常用于编程错误。
- 异常消息应清晰说明问题原因,便于调试。
- 避免过度使用异常处理流程控制。






