0% found this document useful (0 votes)
30 views

Week 11 - Exception Handling

Uploaded by

acercrollercoil
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
30 views

Week 11 - Exception Handling

Uploaded by

acercrollercoil
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 8

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;
System.out.println(num2);
System.out.println("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
*/
System.out.println("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.
*/
System.out.println("Exception occurred");
}
System.out.println("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;
System.out.println("First print statement in try block");
}
catch(ArithmeticException e){
System.out.println("Warning: ArithmeticException");
}
catch(ArrayIndexOutOfBoundsException e){
System.out.println("Warning: ArrayIndexOutOfBoundsException");
}
catch(Exception e){
System.out.println("Warning: Some Other exception");
}
System.out.println("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;
System.out.println(num);
}
catch(ArithmeticException e){
System.out.println("Number should not be divided by zero");
}
/* Finally block will always execute
* even if there is no exception in try block
*/
finally{
System.out.println("This is finally block");
}
System.out.println("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[])
{
System.out.println(JavaFinally.myMethod());
}

4|P ag e
Object Oriented Programming
Exceptions Handling

public static int myMethod()


{
try {
return 112;
}
finally {
System.out.println("This is Finally block");
System.out.println("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{
output.writeObject(writableObject);
}
finally{
op.close();
}
}
catch(IOException e1){
System.out.println(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("inputfile.txt");
}
finally {
if (input != null) {
try {
in.close();
}catch (IOException exp) {
System.out.println(exp);
}
}
}
...
Finally block and System.exit()

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

....
try {
//try block
System.out.println("Inside try block");
System.exit(0)
}
catch (Exception exp) {
System.out.println(exp);
}
finally {
System.out.println("Java finally block");
}
....
In the above example if the System.exit(0) gets called without any exception then finally won’t
execute. However if any exception occurs while calling System.exit(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{
System.out.println("First statement of try block");
int num=45/3;
System.out.println(num);
}
catch(ArrayIndexOutOfBoundsException e){
System.out.println("ArrayIndexOutOfBoundsException");
}
finally{
System.out.println("finally block");
}
System.out.println("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{
System.out.println("First statement of try block");
int num=45/0;
System.out.println(num);
}
catch(ArrayIndexOutOfBoundsException e){
System.out.println("ArrayIndexOutOfBoundsException");
}
finally{
System.out.println("finally block");
}
System.out.println("Out of try-catch-finally block");
}
}
Output:

First statement of try block


finally block
Exception in thread "main" java.lang.ArithmeticException: / by zero
at beginnersbook.com.Example2.main(Details.java:6)
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{
System.out.println("First statement of try block");
int num=45/0;
System.out.println(num);
}
catch(ArithmeticException e){
System.out.println("ArithmeticException");
}
finally{
System.out.println("finally block");
}
System.out.println("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.


https://beginnersbook.com/2013/04/java-finally-block/

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


https://beginnersbook.com/2013/04/java-exception-handling/

8|P ag e

You might also like