异常处理:Java捕获和处理自定义异常示例
在Java中,我们可以自定义异常类来表示应用程序中的特定错误。然后,我们可以在代码中使用try-catch语句来捕获和处理这些异常。
以下是一个简单的自定义异常(CustomException)以及如何用try-catch块处理它的示例:
// 自定义异常类
class CustomException extends Exception {
public CustomException(String message) {
super(message);
}
}
public class ExceptionHandling {
public static void main(String[] args) {
// 在可能出现异常的地方使用try语句
try {
// 这里可能会抛出CustomException
throw new CustomException("This is a custom exception");
// 如果没有抛出异常,代码将正常执行
System.out.println("Normal code execution without exception.");
} catch (CustomException e) {
// 当捕获到自定义异常时,打印错误信息并记录日志
System.err.println("Error caught: " + e.getMessage());
// 在这里添加你的记录日志操作
// ...
}
}
}
在这个示例中,我们创建了一个名为CustomException
的自定义异常类。然后,在main
方法中,我们在可能会抛出这个自定义异常的地方使用try语句。
如果在try块中抛出了CustomException
,那么在catch块中捕获到这个异常,并执行相应的错误处理逻辑。
还没有评论,来说两句吧...