Java异常处理:捕获自定义异常示例
在Java编程中,我们可以创建自己的自定义异常。以下是一个简单的示例,展示如何捕获并处理自定义异常。
首先,我们创建一个名为CustomException
的自定义异常:
public class CustomException extends Exception {
public CustomException(String message) {
super(message);
}
}
然后,在代码中使用try-catch
语句捕获和处理CustomException
:
public class Main {
public static void main(String[] args) {
// 创建一个自定义异常对象
String errorMessage = "This is a custom error message.";
CustomException customException = new CustomException(errorMessage);
try {
// 在可能会抛出异常的地方
processWithPotentialError();
} catch (CustomException e) {
// 处理自定义异常
System.out.println("Handling custom exception: " + e.getMessage());
} catch (Exception anyException) {
// 处理所有类型的异常
System.out.println(" Handling any exception: " + anyException.getMessage());
}
System.out.println("Normal execution after try-catch block.");
}
private static void processWithPotentialError() throws Exception {
// 假设这里可能会抛出自定义异常
int riskyValue = calculateRiskyValue();
if (riskyValue > 10) {
throw new CustomException("Invalid risky value: " + riskyValue);
}
}
private static int calculateRiskyValue() {
// 这里是一个模拟的可能会抛出异常的操作
// 在真实项目中,你需要从数据库、网络等地方获取数据
Thread.sleep(2000); // 假设这里需要执行一段时间来模拟异常
if (Thread.currentThread().isInterrupted()) {
throw new InterruptedException("Thread was interrupted while executing risky operation.");
}
return 15; // 这里返回一个模拟的可能会出问题的结果
}
}
在这个示例中,我们创建了一个名为CustomException
的自定义异常,并在processWithPotentialError()
方法中尝试进行可能抛出异常的操作。如果发生异常,我们就捕获它并处理。
还没有评论,来说两句吧...