java 如何抛异常
抛出异常的基本语法
在Java中,使用throw关键字手动抛出异常。语法格式为:
throw new ExceptionType("Error message");
ExceptionType可以是Java内置异常类(如IllegalArgumentException)或自定义异常类。
抛出内置异常示例
public void checkAge(int age) {
if (age < 18) {
throw new IllegalArgumentException("Age must be at least 18");
}
}
当age小于18时,会抛出IllegalArgumentException并附带错误信息。
创建自定义异常
自定义异常需继承Exception(受检异常)或RuntimeException(非受检异常):
class CustomException extends RuntimeException {
public CustomException(String message) {
super(message);
}
}
使用时:
throw new CustomException("This is a custom error");
受检异常与非受检异常
-
受检异常:必须声明或捕获(如
IOException)public void readFile() throws IOException { throw new IOException("File not found"); } -
非受检异常:无需声明(如
RuntimeException子类)public void validate(int value) { if (value < 0) { throw new RuntimeException("Negative value"); } }
异常链
可通过构造方法传递原始异常:

try {
// 可能出错的代码
} catch (IOException e) {
throw new CustomException("Wrapper message", e);
}
最佳实践
- 优先使用标准异常(如
IllegalArgumentException) - 异常信息应清晰说明错误原因
- 避免过度使用异常处理流程控制
- 自定义异常通常用于业务特定错误
完整示例
public class Account {
private double balance;
public void withdraw(double amount) {
if (amount <= 0) {
throw new IllegalArgumentException("Amount must be positive");
}
if (amount > balance) {
throw new InsufficientFundsException(
"Requested: " + amount + ", Available: " + balance);
}
balance -= amount;
}
}
class InsufficientFundsException extends RuntimeException {
public InsufficientFundsException(String message) {
super(message);
}
}






