From 347f23709056a9397637c0fa8989d2f6ebd08873 Mon Sep 17 00:00:00 2001 From: Nicola Iacovelli Date: Fri, 9 Nov 2018 22:48:09 +0100 Subject: [PATCH] Improved description of finally (#22367) * Improved description of finally Added more examples for the finally block * Grammatical changes --- guide/english/java/finally-keyword/index.md | 12 +++++++++++- 1 file changed, 11 insertions(+), 1 deletion(-) diff --git a/guide/english/java/finally-keyword/index.md b/guide/english/java/finally-keyword/index.md index 13fc611ee0..538d7a1c2c 100644 --- a/guide/english/java/finally-keyword/index.md +++ b/guide/english/java/finally-keyword/index.md @@ -3,7 +3,7 @@ title: Finally --- ## finally -The finally block always executes when the try block exits. This ensures that the finally block is executed even if an unexpected exception occurs. But finally is useful for more than just exception handling — it allows the programmer to avoid having cleanup code accidentally bypassed by a return, continue, or break. Putting cleanup code in a finally block is always a good practice, even when no exceptions are anticipated. +The finally block always executes when the try block exits. This ensures that the finally block is executed even if an unexpected exception occurs. But finally is useful for more than just exception handling — it allows the programmer to avoid having cleanup code accidentally bypassed by a return, continue, or break. Putting cleanup code in a finally block is always a good practice, even when no exceptions are anticipated. It is also useful for closing connections in case of an unexpected exception, for example, it can close an open database connection if an exception is thrown during the try block. ***Example:*** ```java @@ -29,5 +29,15 @@ try { System.out.println("In finally block"); } ``` +***Example*** +``` +try { + //Try to execute a query that can throws an exception + stmt.executeUpdate( "INSERT INTO MyTable( name ) VALUES ( 'my name' ) " ); +} finally { + //Close the DB connection even in case of problem + stmt.close(); +} +``` The above code works fine even though the catch statement is not used.