Java异常处理:自定义异常构造实例
在Java中,自定义异常是为了对特定情况或者错误进行更具体的描述。以下是自定义异常构造实例的步骤:
- 创建一个异常类,例如
MyCustomException
。
public class MyCustomException extends Exception {
// 添加必要的属性和方法
}
- 在构造函数中设置异常信息,可以添加额外的信息如错误码等。
public MyCustomException(String errorMessage, int errorCode) {
super(errorMessage);
this.errorCode = errorCode;
}
- 在你的代码中使用自定义的异常。
public class Main {
public static void main(String[] args) {
try {
// 假设这里发生了MyCustomException
throw new MyCustomException("Error message", 100);
} catch (MyCustomException e) {
System.out.println("Caught custom exception: " + e.getMessage());
System.out.println("Error code: " + e.errorCode);
}
}
}
这样,你就创建了一个自定义异常,并在可能出错的地方抛出了这个异常。
还没有评论,来说两句吧...