Java异常处理:捕获,声明和抛出例子
在Java中,异常处理是通过try-catch-finally块来实现的。以下是一些基本的例子:
捕获特定类型的异常:
try {
int divideByZero = 5 / 0;
} catch (ArithmeticException e) {
System.out.println("Error: Division by zero is not allowed.");
}
声明和抛出自定义异常:
```java
class CustomException extends Exception {
public CustomException(String message) {super(message);
}
}
try {
throw new CustomException(“This is a custom error.”);
} catch (CustomException e) {
System.out.println(“Error: “ + e.getMessage());
}
3. 处理多行代码的异常:
```java
try {
int result = 10 / 0; // 在这里抛出异常
} catch (ArithmeticException e) {
System.out.println("Error: Division by zero is not allowed.");
// 可以在这里进行清理工作,例如关闭连接等
}
以上就是Java中异常处理的一些基本操作。
还没有评论,来说两句吧...