亿迅智能制造网
工业4.0先进制造技术信息网站!
首页 | 制造技术 | 制造设备 | 工业物联网 | 工业材料 | 设备保养维修 | 工业编程 |
home  MfgRobots >> 亿迅智能制造网 >  >> Industrial programming >> java

Java 尝试...捕获

Java 尝试...捕获

在本教程中,我们将通过示例了解 Java 中的 try catch 语句。

try...catch Java中的block用于处理异常,防止程序异常终止。

这是 try...catch 的语法 Java 中的块。

try{
  // code
}
catch(exception) {
  // code
}

try 块包含可能产生异常的代码。

catch 块包含 try 内发生异常时执行的代码 块。

示例:Java try...catch 块

class Main {
  public static void main(String[] args) {

    try {
      int divideByZero = 5 / 0;
      System.out.println("Rest of code in try block");
    }

    catch (ArithmeticException e) {
      System.out.println("ArithmeticException => " + e.getMessage());
    }
  }
}

输出

ArithmeticException => / by zero

在上面的例子中,注意这一行,

int divideByZero = 5 / 0;

在这里,我们试图将一个数字除以 .在这种情况下,会发生异常。因此,我们将此代码包含在 try 中 块。

当程序遇到这个代码时,ArithmeticException 发生。并且,异常被 catch 捕获 阻塞并执行 catch 内的代码 块。

catch 只有在 try 中存在异常时才会执行块 块。

注意 :在 Java 中,我们可以使用 try 没有 catch 的块 堵塞。但是,我们不能使用 catch 没有 try 的块 块。


Java try...finally 块

我们也可以使用 try 块和 finally 块一起。

在这种情况下,无论try块内部是否有异常,都会执行finally块。

示例:Java try...finally 阻塞

class Main {
  public static void main(String[] args) {
    try {
      int divideByZero = 5 / 0;
    }

    finally {
      System.out.println("Finally block is always executed");
    }
  }
}

输出

Finally block is always executed
Exception in thread "main" java.lang.ArithmeticException: / by zero
        at Main.main(Main.java:4)

在上面的例子中,我们使用了 tryfinally 一起阻止 堵塞。我们可以看到try里面的代码 块导致异常。

但是,finally里面的代码 块被执行而不考虑异常。


Java try...catch...finally 块

在Java中,我们也可以在try...catch之后使用finally块 堵塞。例如,

import java.io.*;

class ListOfNumbers {

  // create an integer array
  private int[] list = {5, 6, 8, 9, 2};

  // method to write data from array to a fila
  public void writeList() {
    PrintWriter out = null;

    try {
      System.out.println("Entering try statement");

      // creating a new file OutputFile.txt
      out = new PrintWriter(new FileWriter("OutputFile.txt"));

      // writing values from list array to Output.txt
      for (int i = 0; i < 7; i++) {
        out.println("Value at: " + i + " = " + list[i]);
      }
    }
    
    catch (Exception e) {
      System.out.println("Exception => " + e.getMessage());
    }
    
    finally {
      // checking if PrintWriter has been opened
      if (out != null) {
        System.out.println("Closing PrintWriter");
        // close PrintWriter
        out.close();
      }
      
      else {
        System.out.println("PrintWriter not open");
      }
    }

  }
}

class Main {
  public static void main(String[] args) {
    ListOfNumbers list = new ListOfNumbers();
    list.writeList();
  }
}

输出

Entering try statement
Exception => Index 5 out of bounds for length 5
Closing PrintWriter

在上面的例子中,我们创建了一个名为 list 的数组 和一个名为 output.txt 的文件 .在这里,我们尝试从数组中读取数据并存储到文件中。

注意代码,

for (int i = 0; i < 7; i++) {
  out.println("Value at: " + i + " = " + list[i]);
}

这里,数组的大小是5 并且数组的最后一个元素位于 list[4] .但是,我们正在尝试访问 a[5] 处的元素 和 a[6] .

因此,代码会生成一个被 catch 块捕获的异常。

finally 块总是被执行,我们已经包含了关闭 PrintWriter 的代码 在 finally 块内。

最好使用 finally 块来包含重要的清理代码,例如关闭文件或连接。

注意 :在某些情况下,finally 块不执行:


多个 Catch 块

对于每个 try 块,可以有零个或多个 catch 块。多个catch 块允许我们以不同的方式处理每个异常。

每个catch的参数类型 block 表示它可以处理的异常类型。例如,

class ListOfNumbers {
  public int[] arr = new int[10];

  public void writeList() {

    try {
      arr[10] = 11;
    }
    
    catch (NumberFormatException e1) {
      System.out.println("NumberFormatException => " + e1.getMessage());
    }
    
    catch (IndexOutOfBoundsException e2) {
      System.out.println("IndexOutOfBoundsException => " + e2.getMessage());
    }

  }
}

class Main {
  public static void main(String[] args) {
    ListOfNumbers list = new ListOfNumbers();
    list.writeList();
  }
}

输出

IndexOutOfBoundsException => Index 10 out of bounds for length 10

在本例中,我们创建了一个名为 arr 的整数数组 大小 10 .

由于数组索引从 0 开始 , 数组的最后一个元素在 arr[9] .注意声明,

arr[10] = 11;

在这里,我们尝试为索引 10 赋值 .因此,IndexOutOfBoundException 发生。

try发生异常时 块,


捕获多个异常

从 Java SE 7 及更高版本开始,我们现在可以使用一个 catch 捕获多种类型的异常 块。

这减少了代码重复,提高了代码的简洁性和效率。

catch 可以处理的每种异常类型 使用竖线 | 分隔块 .

它的语法是:

try {
  // code
} catch (ExceptionType1 | Exceptiontype2 ex) { 
  // catch block
}

要了解更多信息,请访问 Java 捕获多个异常。


Java try-with-resources 语句

try-with-resources 语句是一个包含一个或多个资源声明的 try 语句。

它的语法是:

try (resource declaration) {
  // use of the resource
} catch (ExceptionType e1) {
  // catch block
}

资源是在程序结束时关闭的对象。必须在try语句中声明和初始化。

举个例子吧。

try (PrintWriter out = new PrintWriter(new FileWriter("OutputFile.txt")) {
  // use of the resource
}

try-with-resources 语句也称为自动资源管理 .该语句在语句结束时自动关闭所有资源。

要了解更多信息,请访问 java try-with-resources 语句。


java

  1. Java 运算符
  2. Java 评论
  3. Java for-each 循环
  4. Java 字符串
  5. Java 接口
  6. Java 匿名类
  7. Java 异常处理
  8. Java 捕获多个异常
  9. Java try-with-resources
  10. Java 注释
  11. Java 断言
  12. Java 向量