0% found this document useful (0 votes)
68 views8 pages

Understanding Try-Catch-Finally in Java

Uploaded by

acercrollercoil
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
68 views8 pages

Understanding Try-Catch-Finally in Java

Uploaded by

acercrollercoil
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

Object Oriented Programming

Exceptions Handling

MODULE 7 – Exception Handling

Try Catch in Java – Exception handling

In this module we will see try-catch block which is used for exception handling.

Try block

The try block contains set of statements where an exception can occur. A try block is always
followed by a catch block, which handles the exception that occurs in associated try block. A
try block must be followed by catch blocks or finally block or both.

Syntax of try block

try{
//statements that may cause an exception
}
While writing a program, if you think that certain statements in a program can throw an exception,
enclosed them in try block and handle that exception

Catch block

A catch block is where you handle the exceptions, this block must follow the try block. A single
try block can have several catch blocks associated with it. You can catch different exceptions
in different catch blocks. When an exception occurs in try block, the corresponding catch block
that handles that particular exception executes. For example if an arithmetic exception occurs
in try block then the statements enclosed in catch block for arithmetic exception executes.

Syntax of try catch in java

try
{
//statements that may cause an exception
}
catch (exception(type) e(object))
{
//error handling code
}
Example: try catch block

If an exception occurs in try block then the control of execution is passed to the corresponding catch
block. A single try block can have multiple catch blocks associated with it, you should place the catch
blocks in such a way that the generic exception handler catch block is at the last(see in the example
below).
The generic exception handler can handle all the exceptions but you should place is at the end, if you
place it at the before all the catch blocks then it will display the generic message. You always want to
give the user a meaningful message for each type of exception rather then a generic message.

class Example1 {
public static void main(String args[]) {
int num1, num2;
try {

1|P ag e
Object Oriented Programming
Exceptions Handling

/* We suspect that this block of statement can throw


* exception so we handled it by placing these statements
* inside try and handled the exception in catch block
*/
num1 = 0;
num2 = 62 / num1;
[Link](num2);
[Link]("Hey I'm at the end of try block");
}
catch (ArithmeticException e) {
/* This block will only execute if any Arithmetic exception
* occurs in try block
*/
[Link]("You should not divide a number by zero");
}
catch (Exception e) {
/* This is a generic Exception handler which means it can handle
* all the exceptions. This will execute if the exception is not
* handled by previous catch blocks.
*/
[Link]("Exception occurred");
}
[Link]("I'm out of try-catch block in Java.");
}
}
Output:

You should not divide a number by zero


I'm out of try-catch block in Java.
Multiple catch blocks in Java

The example we seen above is having multiple catch blocks, lets see few rules about multiple catch
blocks with the help of examples. To read this in detail, see catching multiple exceptions in java.
1. As I mentioned above, a single try block can have any number of catch blocks.
2. A generic catch block can handle all the exceptions. Whether it is ArrayIndexOutOfBoundsException
or ArithmeticException or NullPointerException or any other type of exception, this handles all of
them.

catch(Exception e){
//This catch block catches all the exceptions
}
If you are wondering why we need other catch handlers when we have a generic that can handle all.
This is because in generic exception handler you can display a message but you are not sure for which
type of exception it may trigger so it will display the same message for all the exceptions and user may
not be able to understand which exception occurred. Thats the reason you should place is at the end
of all the specific exception catch blocks

3. If no exception occurs in try block then the catch blocks are completely ignored.
4. Corresponding catch blocks execute for that specific type of exception: catch(ArithmeticException
e) is a catch block that can hanlde ArithmeticException catch(NullPointerException e) is a catch block
that can handle NullPointerException.

2|P ag e
Object Oriented Programming
Exceptions Handling

Example of Multiple catch blocks


class Example2{
public static void main(String args[]){
try{
int a[]=new int[7];
a[4]=30/0;
[Link]("First print statement in try block");
}
catch(ArithmeticException e){
[Link]("Warning: ArithmeticException");
}
catch(ArrayIndexOutOfBoundsException e){
[Link]("Warning: ArrayIndexOutOfBoundsException");
}
catch(Exception e){
[Link]("Warning: Some Other exception");
}
[Link]("Out of try-catch block...");
}
}
Output:

Warning: ArithmeticException
Out of try-catch block...
In the above example there are multiple catch blocks and these catch blocks executes sequentially
when an exception occurs in try block. Which means if you put the last catch block ( catch(Exception
e)) at the first place, just after try block then in case of any exception this block will execute as it can
handle all exceptions. This catch block should be placed at the last to avoid such situations.

Java Finally block – Exception handling

In this guide, we will see finally block which is used along with try-catch. A finally block contains all
the crucial statements that must be executed whether exception occurs or not. The statements
present in this block will always execute regardless of whether exception occurs in try block or not
such as closing a connection, stream etc.

Syntax of Finally block

try {
//Statements that may cause an exception
}
catch {
//Handling exception
}
finally {
//Statements to be executed
}
A Simple Example of finally block

Here you can see that the exception occurred in try block which has been handled in catch block, after
that finally block got executed.

3|P ag e
Object Oriented Programming
Exceptions Handling

class Example
{
public static void main(String args[]) {
try{
int num=121/0;
[Link](num);
}
catch(ArithmeticException e){
[Link]("Number should not be divided by zero");
}
/* Finally block will always execute
* even if there is no exception in try block
*/
finally{
[Link]("This is finally block");
}
[Link]("Out of try-catch-finally");
}
}
Output:

Number should not be divided by zero


This is finally block
Out of try-catch-finally
Few Important points regarding finally block

1. A finally block must be associated with a try block, you cannot use finally without a try block. You
should place those statements in this block that must be executed always.

2. Finally block is optional, as we have seen in previous tutorials that a try-catch block is sufficient
for exception handling, however if you place a finally block then it will always run after the execution
of try block.

3. In normal case when there is no exception in try block then the finally block is executed after try
block. However if an exception occurs then the catch block is executed before finally block.

4. An exception in the finally block, behaves exactly like any other exception.

5. The statements present in the finally block execute even if the try block contains control transfer
statements like return, break or continue. Let’s see an example to see how finally works when return
statement is present in try block:

Another example of finally block and return statement

You can see that even though we have return statement in the method, the finally block still runs.

class JavaFinally
{
public static void main(String args[])
{
[Link]([Link]());
}

4|P ag e
Object Oriented Programming
Exceptions Handling

public static int myMethod()


{
try {
return 112;
}
finally {
[Link]("This is Finally block");
[Link]("Finally block ran even after return statement");
}
}
}
Output of above program:

This is Finally block


Finally block ran even after return statement
112
To see more examples of finally and return refer: Java finally block and return statement.

Cases when the finally block doesn’t execute

The circumstances that prevent execution of the code in a finally block are:
– The death of a Thread
– Using of the System. exit() method.
– Due to an exception arising in the finally block.

Finally and Close()

close() statement is used to close all the open streams in a program. Its a good practice to use close()
inside finally block. Since finally block executes even if exception occurs so you can be sure that all
input and output streams are closed properly regardless of whether the exception occurs or not.

For example:

....
try{
OutputStream osf = new FileOutputStream( "filename" );
OutputStream osb = new BufferedOutputStream(opf);
ObjectOutput op = new ObjectOutputStream(osb);
try{
[Link](writableObject);
}
finally{
[Link]();
}
}
catch(IOException e1){
[Link](e1);
}
...
Finally block without catch

A try-finally block is possible without catch block. Which means a try block can be used with finally
without having a catch block.

5|P ag e
Object Oriented Programming
Exceptions Handling

...
InputStream input = null;
try {
input = new FileInputStream("[Link]");
}
finally {
if (input != null) {
try {
[Link]();
}catch (IOException exp) {
[Link](exp);
}
}
}
...
Finally block and [Link]()

[Link]() statement behaves differently than return statement. Unlike return statement
whenever [Link]() gets called in try block then Finally block doesn’t execute. Here is a code
snippet that demonstrate the same:

....
try {
//try block
[Link]("Inside try block");
[Link](0)
}
catch (Exception exp) {
[Link](exp);
}
finally {
[Link]("Java finally block");
}
....
In the above example if the [Link](0) gets called without any exception then finally won’t
execute. However if any exception occurs while calling [Link](0) then finally block will be
executed.

try-catch-finally block

 Either a try statement should be associated with a catch block or with finally.
 Since catch performs exception handling and finally performs the cleanup, the best approach
is to use both of them.

Syntax:

try {
//statements that may cause an exception
}
catch (…) {
//error handling code
}
finally {
//statements to be executed
}

6|P ag e
Object Oriented Programming
Exceptions Handling

Examples of Try catch finally blocks

Example 1: The following example demonstrate the working of finally block when no exception occurs
in try block

class Example1{
public static void main(String args[]){
try{
[Link]("First statement of try block");
int num=45/3;
[Link](num);
}
catch(ArrayIndexOutOfBoundsException e){
[Link]("ArrayIndexOutOfBoundsException");
}
finally{
[Link]("finally block");
}
[Link]("Out of try-catch-finally block");
}
}
Output:

First statement of try block


15
finally block
Out of try-catch-finally block
Example 2: This example shows the working of finally block when an exception occurs in try block but
is not handled in the catch block:

class Example2{
public static void main(String args[]){
try{
[Link]("First statement of try block");
int num=45/0;
[Link](num);
}
catch(ArrayIndexOutOfBoundsException e){
[Link]("ArrayIndexOutOfBoundsException");
}
finally{
[Link]("finally block");
}
[Link]("Out of try-catch-finally block");
}
}
Output:

First statement of try block


finally block
Exception in thread "main" [Link]: / by zero
at [Link]([Link])
As you can see that the system generated exception message is shown but before that the finally block
successfully executed.

7|P ag e
Object Oriented Programming
Exceptions Handling

Example 3: When exception occurs in try block and handled properly in catch block

class Example3{
public static void main(String args[]){
try{
[Link]("First statement of try block");
int num=45/0;
[Link](num);
}
catch(ArithmeticException e){
[Link]("ArithmeticException");
}
finally{
[Link]("finally block");
}
[Link]("Out of try-catch-finally block");
}
}
Output:

First statement of try block


ArithmeticException
finally block
Out of try-catch-finally block

Sources:

Singh, C. (2013). Java – Finally Block.


[Link]

Singh, C. (2013). Java – Exception Handling.


[Link]

8|P ag e

Common questions

Powered by AI

A 'finally' block does not execute in Java if there is a system exit call (System.exit()), which ends the program execution before reaching the 'finally' block. Additionally, if there is an exception thrown within the 'finally' block itself that is not caught, it can prevent completion of the 'finally' block. Lastly, thread death due to abrupt termination can also prevent the execution of the 'finally' block .

In Java exception handling, the 'catch' block is used to handle exceptions that occur in the associated 'try' block, allowing specific responses to different exception types. Conversely, a 'finally' block is used to execute essential code that should run regardless of whether an exception occurred, such as cleanup activities like closing resources. While 'catch' addresses specific exception handling, 'finally' ensures code execution for resource management and termination tasks .

Yes, a 'try' block can be used without a 'catch' block in Java when associated with a 'finally' block. This is appropriate when cleanup or resource management is necessary after executing a block of code, and there is no specific need to handle exceptions differently. The 'finally' block ensures that crucial code, such as closing connections or streams, runs regardless of exceptions .

When an exception is handled in the 'catch' block, the associated catch block executes, handling the exception and usually delivering a programmer-defined message, followed by the execution of the 'finally' block. If an exception is not handled (i.e., there is no relevant catch block), the exception will propagate, possibly terminating the program, but the 'finally' block will still execute before stopping unless a system exit occurs. Thus, the 'finally' block always runs after 'catch' or propagating exceptions, providing a mechanism for cleanup .

The 'try' block in Java exception handling is used to enclose the code that might throw exceptions. The purpose is to detect errors during execution and allow the program to handle these errors, preventing abrupt termination. The 'try' block must be followed by at least one 'catch' block to handle exceptions, or a 'finally' block to execute code regardless of exceptions, or both. It is essential to place statements that can throw exceptions within this block for effective exception handling .

Some good practices for using the 'finally' block in Java for resource management include closing resources like I/O streams or database connections within the 'finally' block to ensure they are closed regardless of whether an exception occurs. This ensures resource leaks are avoided, and system resources are released. Additionally, using 'finally' helps in maintaining code that is cleaner and less prone to resource leaks by guaranteeing the execution of cleanup code .

An exception within the 'finally' block can disrupt the execution of cleanup code and potentially lead to further exceptions. It is crucial to handle exceptions in the 'finally' block using nested try-catch statements to ensure that resources are adequately released and program stability is maintained. Failing to handle exceptions within 'finally' might prevent other essential code from executing and cause resource leaks or instability .

Placing a generic catch block at the end of multiple specific catch blocks in Java is recommended to ensure specific exceptions are caught and handled appropriately before handling all exceptions generically. This practice allows for more informative error handling by catching and addressing specific exceptions with relevant messages. If the generic catch block is placed first, it would catch all exceptions as a general Exception, preventing specific handlers from executing and leading to less informative error messages .

The benefits of using multiple catch blocks include providing specific handlers for different exception types, allowing more meaningful and informative error messages and recovery strategies tailored to specific errors. This specificity enhances the robustness and readability of the code. Potential issues include increased complexity and potential oversight if catch blocks are not ordered correctly, leading to catch blocks with less relevant messages capturing exceptions too broadly or inconsistencies in exception handling strategies .

The order of catch blocks affects exception handling in Java because catch blocks are evaluated in the order they appear after the try block. Specific exceptions should be caught first, and more general exceptions later. If a general catch block (Exception) precedes specific ones, it will catch all exceptions and prevent specific handlers from executing. Therefore, to ensure precise handling, catch blocks must be ordered from the most specific exceptions to the most generic .

You might also like