Java Basics – Try, Catch, Finally

Here a summary of these keywords:

1. Try – code enclosed in a “try” {} block is to be handled by a “catch” or a “finally” block.

example:

try{

} catch {

} finally {

}

We can also make blocks with catch only and finally only.

2. Catch – is used to handle Exceptions , we can specify the type of Exception to catch , and place inside this block on how to handle it. The catch block is important to filter out selected Exceptions and decide a logic on how to handle it. Here are two examples below.

A.) Catch and Stop

} catch ( SampleException e ){

// do something or log something here

//This Exception is caught therefore it wont cause the program to crash

}

B.) Catch and Throw

} catch ( SampleException e ){

//do something or log something here

throw new Exception();

//After catching this exception , another exception is thrown, which may be handled by another code.

//Unhandled Exceptions will cause the program to crash

}

NOTES on Exceptions:

  • As advised, Do not catch Low-Level and Runtime Exceptions, Only catch custom / High-Level Exceptions

3. Finally – this block will always execute before the return code, Even if Exceptions occur. A thrown Exception on a method call will cease to execute the succeeding code lines, but the finally will block will always be executed just before the end/return of the method.

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s