Javatpoint Logo
Javatpoint Logo

Java Program to use Finally Block for Catching Exceptions

A block is one of the most helpful industry practices in the IT field. During the development cycle of the IT project, there will be a need to create and maintain some necessary code. These essential lines of code have to be put in the try block to label them as clean code, for instance, the closing of the file in the developed project or closing the established connection.

Finally, the block is broadly used in three cases, and they are discussed below with relevant code in the java programming language.

Case 1: When an Exception doesn't Rise

Java Code

Output:

java -cp / tmp /pk kY 1yo G xa  JTP
hey! Coder, we are inside the try block now
42
Hey, code,r finally: i executed consistently has taken place!

Case 2: When the Exception Rises and is Handled by the Catch Block

Java Code

Output:

java -cp  /tmp /pk kY 1y oG X a JTP
hey! Coder, we are inside the try block now
hey, coder, the catch: exception has been handled.
Hey coder, finally: i executed consistently has taken place!

Case 3: When Exception Rise and are not Handled by the Catch Block

Java Code

Output:

java -cp  /tm p/pkkY 1yo GXa JTP
hey! Coder, we are inside the try block nowhere coder, finally: i executed always has taken place!
Exception in thread "main" java. Lang.ArithmeticException: / by zero at JTP.main(JTP.java:17)






Youtube For Videos Join Our Youtube Channel: Join Now

Feedback


Help Others, Please Share

facebook twitter pinterest

Learn Latest Tutorials


Preparation


Trending Technologies


B.Tech / MCA