Try-Catch-Finally

by | Dec 20, 2020 | Java

Home » Java » Try-Catch-Finally

Try-Catch-Finally

Try, Catch, and Finally are three different blocks that go one after the other in the order in which they are named. First comes the Try block inside which is a small part of the code that is considered to give exception(s). This is followed by the Catch block. This block is the exception handler. It contains the generated exception type in its parameter and normally executes a print statement inside it. The Finally block is the last in the list. This block contains code that is responsible for executing important parts of code like closing connection, stream, etc. What makes the Finally block different from the other blocks is that it gets executed anyway whether the exception has been caught or not.

Example

class SampleFinally
{
public static void main ( String args[] )
{
try
{
int data=25/5;
System.out.println ( data );
}

catch ( NullPointerException e )
{
System.out.println (e);
}

finally
{
System.out.println ( "finally block is always executed" );
}
System.out.println ( "Hello World" );
}
}

OUTPUT

5
finally block is always executed
Hello World

In this case, since there is no exception at all after the try block is executed, the program skips the catch block and goes to the finally block. Even if there was an exception, the Finally block would have been executed and that string would be printed out. Thereafter, the rest of the program is executed.

Author

0 Comments

Submit a Comment

Your email address will not be published. Required fields are marked *

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

Author