Why You Need to Close the Java Streams in Finally Block?
In Java finally block is a block used to execute important and common code. The finally block is mostly used during exception handling with try and catch to close streams and files. The code in finally block is executed irrespective of whether there is an exception or not. This ensures that all the opened files are properly closed and all the running threads are properly terminated. So, the data in the files will not be corrupted and the user is on the safe-side.
Finally block is executed after try and catch block. The flow of the code is:
Below mentioned are two examples of when exception is caused and when it is not caused.
We will observe that finally block is executed in both our codes.
Example 1: With exception in code
Open files exception caught java.lang.ArithmeticException: / by zero Inside finally block Close files
Example 2: Without exception
Open files After dividing a and b ans is 9 Inside finally block Close files