English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية

Tutoriel de base Java

Contrôle de flux Java

Java Tableau

Java Programmation Orientée Objet (I)

Java Programmation Orientée Objet (II)

Java Programmation Orientée Objet (III)

Gestion des exceptions Java

Java Liste (List)

Java Queue (file d'attente)

Java Map Collection

Java Set Collection

Java Entrée Sortie (I/O)

Java Liseur/Écrivain

Autres sujets Java

Java try-with-Resources

Dans ce tutoriel, nous allons apprendre try-with-L'expression resources ferme les ressources automatiquement.

try-with-L'expression resources ferme automatiquement toutes les ressources à la fin de l'expression. Les ressources sont des objets à fermer à la fin du programme.

Sa syntaxe est :

try (déclaration de resource) {
  // Utilisation de la ressource
} catch (ExceptionType e1) {
  // Bloc catch
}

À partir de la syntaxe ci-dessus, nous pouvons déclarer try de la manière suivante :-with-Expression resources :

  1. Déclarez et instanciez les ressources dans la clause try.

  2. Spécifiez et traitez toutes les exceptions pouvant être levées lors de la fermeture des ressources.

Attention :try-with-L'expression resources ferme toutes les ressources implémentant l'interface AutoCloseable.

Permettons d'implémenter try-with-Par exemple, une expression resources utilisée dans une expression try.

示例1: try-with-Resources

import java.io;*;
class Main {
  public static void main(String[] args) {
    String line;
    try(BufferedReader br = new BufferedReader(new FileReader("test.txt"))) {
      while ((line = br.readLine()) != null) {
        System.out.println("Line => ")}+line);
      }
    } catch (IOException e) {
      System.out.println("IOException in try block => "); + e.getMessage());
    }
  }
}

Si le fichier test.txt n'est pas trouvé, il est affiché.

IOException dans try-with-Bloc resources => test.txt (Fichier ou répertoire introuvable)

Si le fichier test.txt est trouvé, il est affiché.

Entrée dans try-with-Bloc resources
Ligne => ligne test

Dans cet exemple, l'instance BufferedReader que nous utilisons lit les données à partir du fichier test.txt.

Dans try-with-Déclarer et instancier BufferedReader dans une expression resources garantit sa fermeture, qu'elle se termine normalement ou qu'une exception soit levée.

如果发生异常,则可以使用异常处理块或throws关键字对其进行处理。

抑制异常

在上面的示例中,在以下情况下可以从try-with-resources语句引发异常:

  • 找不到test.txt文件。

  • 关闭BufferedReader对象。

也可以从try块中引发异常,因为文件读取可能随时因多种原因而失败。

如果从try块和try-with-resources语句都抛出异常,则会抛出try块中的异常,并抑制try-with-resources语句中的异常。

检索抑制的异常

In Java 7和更高版本中,可以通过Throwable.getSuppressed()从try块引发的异常中调用方法来检索抑制的异常。

此方法返回所有抑制的异常的数组。我们在catch块中得到了抑制的异常。

catch (IOException e) {
  System.out.println("Exception lancée=>" + e.getMessage());
  Throwable[] suppressedExceptions = e.getSuppressed();
  for (int i = 0; i < suppressedExceptions.length; i++) {
    System.out.println("Exception supprimée=>" + suppressedExceptions[i]);
  }
}

使用try-with-resources的优势

这是使用try-with-resources的优点:

1.finally块不需要关闭资源

In Java 7引入此功能之前,我们必须使用该finally块来确保关闭资源以避免资源泄漏。

这是一个类似于示例1的程序。但是,在此程序中,我们使用了finally块来关闭资源。

示例2:使用finally块关闭资源

import java.io;*;
class Main {
  public static void main(String[] args) {
    BufferedReader br = null;
    String line;
    try {
      System.out.println("Entrez dans le bloc try");
      br = new BufferedReader(new FileReader("test.txt"));
      while ((line = br.readLine()) != null) {
        System.out.println("Line => ")}+line);
      }
    } catch (IOException e) {
      System.out.println("IOException in try block => "); + e.getMessage());
    } finally {
      System.out.println("进入 finally 块");
      try {
        if (br != null) {
          br.close();
        }
      } catch (IOException e) {
        System.out.println("IOException in finally block => ");+e.getMessage());
      }
    }
  }
}

输出结果

进入try 块
Line => line from test.txt 文件
进入 finally 块

从上面的示例可以看出,使用finally块来清理资源使代码更加复杂。

您注意到finally块中的try ... catch块吗? 这是因为在关闭此finally块内的BufferedReader实例时也可能发生IOException,因此也将其捕获并处理。

try-with-resources语句执行自动资源管理。我们不需要显式关闭资源,因为JVM会自动关闭它们。这使代码更具可读性,更易于编写。

2.try-with-resources 多个资源

我们可以try-with-resources使用分号将多个资源分开,从而在语句中声明多个资源;

示例3:尝试使用多种资源

import java.io;*;
import java.util;*;
class Main {
  public static void main(String[] args) throws IOException {
    try (Scanner scanner = new Scanner(new File("testRead.txt"))) { 
      PrintWriter writer = new PrintWriter(new File("testWrite.txt")) {
      while (scanner.hasNext()) {
        writer.print(scanner.nextLine());
      }
    }
  }
}

Si l'exécution du programme ne génère aucune exception, l'objet Scanner lit une ligne du fichier testRead.txt et l'écrit dans le fichier testWrite.txt.

When making multiple declarations, try-with-The resources statement closes these resources in reverse order. In this example, the PrintWriter object is closed first, followed by the Scanner object.

Java 9 try-with-resources enhancement

In Java 7In, the try-with-The resources statement has a limitation. The resource must be declared locally within its block.

try (Scanner scanner = new Scanner(new File("testRead.txt"))) {
  // code
}

If we use Java 7If resources are declared outside the block, an error message will be thrown.

Scanner scanner = new Scanner(new File("testRead.txt"));
try (scanner) {
  // code
}

To resolve this error, Java 9 The try has been improved-with-The resources statement is used so that resources can be used even if they are not declared locally. The code now will execute without throwing any compilation errors.