English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية
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 :
Déclarez et instanciez les ressources dans la clause try.
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.
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的优点:
In Java 7引入此功能之前,我们必须使用该finally块来确保关闭资源以避免资源泄漏。
这是一个类似于示例1的程序。但是,在此程序中,我们使用了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会自动关闭它们。这使代码更具可读性,更易于编写。
我们可以try-with-resources使用分号将多个资源分开,从而在语句中声明多个资源;
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.
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.