java 如何抛出异常
抛出异常的方法
在 Java 中,异常可以通过 throw 关键字手动抛出。异常必须是 Throwable 或其子类的实例。以下是几种常见的抛出异常的方式。
抛出已定义的异常
直接使用 Java 内置的异常类,例如 IllegalArgumentException 或 NullPointerException。

if (input == null) {
throw new NullPointerException("Input cannot be null");
}
自定义异常类
通过继承 Exception 或 RuntimeException 创建自定义异常类。
class CustomException extends RuntimeException {
public CustomException(String message) {
super(message);
}
}
// 使用自定义异常
throw new CustomException("This is a custom exception");
在方法中声明异常
如果方法可能抛出受检异常(checked exception),需要在方法签名中使用 throws 声明。

public void readFile(String path) throws IOException {
if (!fileExists(path)) {
throw new IOException("File not found: " + path);
}
}
异常链
在捕获异常后,可以将其包装为另一种异常并重新抛出,保留原始异常信息。
try {
// 可能抛出 IOException 的代码
} catch (IOException e) {
throw new RuntimeException("Failed to process file", e);
}
断言异常
使用 assert 抛出 AssertionError,通常用于调试或测试场景。
assert value > 0 : "Value must be positive";
注意事项
- 受检异常(checked exception)必须在方法签名中声明或捕获。
- 非受检异常(unchecked exception)如
RuntimeException及其子类可以不声明。 - 异常消息应清晰明确,便于调试和问题定位。






