Use finally block in java | Exception handling

Finally block in java is very important, it has crucial statements that must be executed whether an exception occurs or not. A “finally bock” is used with a try-catch block in java. It follows try or catch block.

Important: Java finally block is always executed whether an exception is handled or not. In some cases, it will fail- When finally block is not executed.

Use finally block in java

Example of finally block in java

We will see multiple examples with different cases.

Case 1: Without Exception

We will check a “finally block” executed or not if there is no exception on the try block.

Output:

10.555555
finally block is always executed

Case 2: Exception occurs

In this case, we will check what if exception occurs and handled.

Output:

java.lang.ArithmeticException: / by zero
finally block is always executed

Q: When finally block is not executed in java?

Answer: If System.exit() invoked in a try block, then “finally block” will not call. See below example:-

To know more about it: – When finally block is not executed

Q: Why use java finally?

Answer: You can use finally in java to avoid having cleanup code accidentally bypassed by a returncontinue, or break. Putting cleanup code in a finally block is always a good practice, even when no exceptions are anticipated.

Typically it used for closing files, network connections, etc. 

Q: Can we use java try and finally blocks without a catch?

Answer: Yes, you can use try and finally together without catch block.As you know finally block always executes even if you have an exception or return statement in try block except in case of System.exit().

See the below example for it:-

Output: you can see an error but still finally block code executed.

java try and finally blocks without a catch

Do comment if you have any doubts and suggestions on this tutorial.

Note: This example (Project) is developed in IntelliJ IDEA 2018.2.6 (Community Edition)
JRE: 11.0.1
JVM: OpenJDK 64-Bit Server VM by JetBrains s.r.o
macOS 10.14.1
Java version 11
All Java try catch Java Example codes are in Java 11, so it may change on different from Java 9 or 10 or upgraded versions.


Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.