java自定义异常需显式定义string message和throwable cause双参构造函数并调用super(message, cause);根据是否强制处理选择继承exception或runtimeexception;建议补充单参、无参等常用构造函数;可包装底层异常保留堆栈信息。

Java中自定义异常类,若要支持同时传入 String message 和 Throwable cause,需显式定义对应构造函数,并调用父类(如 Exception 或 RuntimeException)的双参构造方法。
继承合适的父类
根据异常是否需要强制处理,选择继承 Exception(检查型异常)或 RuntimeException(非检查型异常)。两者都提供 String, Throwable 的构造函数,可直接复用。
编写双参构造函数
在自定义异常类中声明构造函数,参数顺序为 String message 和 Throwable cause,并在函数体内通过 super(message, cause) 调用父类对应构造方法:
public class MyCustomException extends Exception {
public MyCustomException(String message, Throwable cause) {
super(message, cause);
}
}
可选:补充其他常用构造函数
为提升易用性,通常一并提供以下构造函数:
-
MyCustomException(String message)→ 调用super(message) -
MyCustomException(Throwable cause)→ 调用super(cause) - 无参构造函数
MyCustomException()→ 调用super()
使用示例
抛出时可包装底层异常,保留原始堆栈信息:
try {
// 可能抛出 IOException
Files.readAllBytes(Paths.get("missing.txt"));
} catch (IOException e) {
throw new MyCustomException("读取配置文件失败", e);
}
这样既提供了业务含义的提示消息,又不丢失原始异常的根因和堆栈,便于排查。
Java免费学习笔记:立即使用
解锁 Java 大师之旅:从入门到精通的终极指南











