Java中的异常处理:自定义Exception示例
在Java中,异常是一种程序运行过程中出现的问题。当程序遇到无法预料的情况时,会抛出一个异常。为了更好地管理这些异常,我们可以自定义异常。
下面是一个简单的自定义Exception示例:
// 定义自定义异常类
public class CustomException extends Exception {
// 自定义构造函数
public CustomException(String message) {
super(message);
}
// 示例方法,触发自定义异常
public static void main(String[] args) {
try {
// 假设这里发生了我们自定义的异常
throw new CustomException("This is a custom exception.");
} catch (CustomException e) {
System.out.println("Caught the custom exception: " + e.getMessage());
}
}
}
在这个示例中,我们创建了一个名为CustomException
的自定义异常类。然后在main
方法中,当一个CustomException
被抛出时,我们会捕获这个异常并打印相关信息。
还没有评论,来说两句吧...