Java异常处理:捕获,声明和抛出例子

原创 布满荆棘的人生 2024-09-25 18:15 166阅读 0赞

在Java中,异常处理是通过try-catch-finally块来实现的。以下是一些基本的例子:

  1. 捕获特定类型的异常:

    1. try {
    2. int divideByZero = 5 / 0;
    3. } catch (ArithmeticException e) {
    4. System.out.println("Error: Division by zero is not allowed.");
    5. }
  2. 声明和抛出自定义异常:
    ```java
    class CustomException extends Exception {
    public CustomException(String message) {

    1. super(message);

    }
    }

try {
throw new CustomException(“This is a custom error.”);
} catch (CustomException e) {
System.out.println(“Error: “ + e.getMessage());
}

  1. 3. 处理多行代码的异常:
  2. ```java
  3. try {
  4. int result = 10 / 0; // 在这里抛出异常
  5. } catch (ArithmeticException e) {
  6. System.out.println("Error: Division by zero is not allowed.");
  7. // 可以在这里进行清理工作,例如关闭连接等
  8. }

以上就是Java中异常处理的一些基本操作。

文章版权声明:注明蒲公英云原创文章,转载或复制请以超链接形式并注明出处。

发表评论

表情:
评论列表 (有 0 条评论,166人围观)

还没有评论,来说两句吧...

相关阅读