java如何抛出异常
抛出异常的方法
在Java中,可以通过throw关键字手动抛出异常。异常可以是Java内置的异常类,也可以是自定义的异常类。
throw new ExceptionType("Error message");
抛出内置异常
Java提供了许多内置异常类,如IllegalArgumentException、NullPointerException等。可以根据具体场景选择合适的异常类型。
if (input < 0) {
throw new IllegalArgumentException("Input cannot be negative");
}
创建自定义异常
如果需要更具体的异常类型,可以创建自定义异常类。自定义异常通常继承自Exception或RuntimeException。

public class CustomException extends Exception {
public CustomException(String message) {
super(message);
}
}
使用时:
throw new CustomException("This is a custom exception");
在方法中声明异常
如果方法内部抛出检查型异常(checked exception),必须在方法签名中使用throws关键字声明。

public void riskyMethod() throws IOException {
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");
}
return a / b;
}
异常链
可以通过异常链将底层异常包装为高层异常,保留原始异常信息。
try {
// Some code that throws IOException
} catch (IOException e) {
throw new CustomException("Failed to process data", e);
}
最佳实践
- 为异常提供清晰的描述信息
- 优先使用最具体的异常类型
- 避免捕获异常后仅打印堆栈而不处理
- 自定义异常应包含有意义的构造方法
- 检查型异常用于可恢复情况,未检查异常用于编程错误





