Home » Java Basics » try/catch/finally » Try-catch Java Example

About Konstantina Dimtsa

Konstantina Dimtsa
Konstantina has graduated from the Department of Informatics and Telecommunications in National and Kapodistrian University of Athens (NKUA) and she is currently pursuing M.Sc studies in Advanced Information Systems at the same department. She is also working as a research associate for NKUA in the field of telecommunications. Her main interests lie in software engineering, web applications, databases and telecommunications.

Try-catch Java Example

In this example we will show how to use the try-catch exception handler. An exception is an error which may occur during the execution of a program and denotes that the normal flow of the program should be interrupted. NullPointerException, IOException, ArithmeticException, ArrayIndexOutOfBoundsException, are some among others commonly seen exceptions. Those exceptions can be handled by some block of code which is surrounded by the statements trycatch. This block of code is called exception handler. Also, the exception handler may optionally include the finally block.

1. Try – Catch – Finally Blocks

  • try block
  • The try block encloses the block of code that may throw an exception.

    try {
    //code that may throw exception
    }
    //catch,finally blocks

  • catch block
  • The catch block is always associated with a try statement and encloses the type of the exception that may arise as well as the block of code that should be executed when the exception is handled.

    try {

    } catch (TypeOfException e) {

    }

    More than one exceptions may arise during the execution of a block of code, thus more than one catch blocks can be associated with a single try:

    try {

    } catch (TypeOfException e) {

    } catch (TypeOfException e) {

    }. . . .

  • finally block
  • The finally block is optional, however its usage is recommended. The finally block encloses a block of code that will be definitely executed regardless of the thrown exception. It usually contains cleanup code so that memory or other resources will be released, even if an exception occurs.

2. Example of try-catch-finally blocks

Create a java class named JavaTryCatchExample.java with the following code:

JavaTryCatchExample.java

package com.javacodegeeks.javabasics.trycatch;

import java.util.ArrayList;
import java.util.List;

public class JavaTryCatchExample {
	public static void main(String[] args) {
		List list = new ArrayList();
		list.add(3);
		list.add(5);
		list.add(0);
		
		try{
			System.out.println("A list element is: "+list.get(5));
			
		}catch(IndexOutOfBoundsException e){
			e.printStackTrace();
		}
	}
}

In the above code, we have defined an ArrayList of Integers which contains 3 elements: 3, 5, 0. If we try to print an element in the index 5 (which is invalid, as the list contains only three elements), the program will face an IndexOutOfBoundsException.

If we run the above code, we will have the following results:

  • Output:
java.lang.IndexOutOfBoundsException: Index: 5, Size: 3
	at java.util.ArrayList.rangeCheck(Unknown Source)
	at java.util.ArrayList.get(Unknown Source)
	at com.javacodegeeks.javabasics.trycatch.JavaTryCatchExample.main(JavaTryCatchExample.java:14)

Let’s slightly change the above code, so as to include one more catch block as well as the finally statement. The previous code will now look like this:

package com.javacodegeeks.javabasics.trycatch;

import java.util.ArrayList;
import java.util.List;

public class JavaTryCatchExample {
	public static void main(String[] args) {
		List list = new ArrayList();
		list.add(3);
		list.add(5);
		list.add(0);
		
		try{
			//System.out.println("A list element is: "+list.get(5));
			
			int x = list.get(1);
			int y = list.get(2);
			
			System.out.println("Division of x/y is: "+(x/y));
                        
		}catch(IndexOutOfBoundsException e){
			e.printStackTrace();
		}catch(ArithmeticException e){
			e.printStackTrace();
		}finally{
			System.out.println("I will be executed, no matter what :-)");
		}
		
	}
}

In the above code, we have commented the statement that caused the exception previously, so as to demonstrate one more type of exception called ArithmeticException. In this case, the specific exception occurs because we are trying to divide by zero, which is not allowed. Also, we can observe that there is a finally statement, which will be executed regardless of the occurrence of the exception.

If we run the above code, we will have the following results:

  • Output:
java.lang.ArithmeticException: / by zero
	at com.javacodegeeks.javabasics.trycatch.JavaTryCatchExample.main(JavaTryCatchExample.java:19)
        I will be executed, no matter what :-)

In the results, we can see that the block of code surrounded by the finally statement is executed.

3. Download the source code

This was an example of the try-catch exception handler in Java. You can download the source code from here: JavaTryCatchExample.zip

Do you want to know how to develop your skillset to become a Java Rockstar?

Subscribe to our newsletter to start Rocking right now!

To get you started we give you our best selling eBooks for FREE!

1. JPA Mini Book

2. JVM Troubleshooting Guide

3. JUnit Tutorial for Unit Testing

4. Java Annotations Tutorial

5. Java Interview Questions

6. Spring Interview Questions

7. Android UI Design

and many more ....

 

Want to take your Java Skills to the next level?
Grab our programming books for FREE!
  • Save time by leveraging our field-tested solutions to common problems.
  • The books cover a wide range of topics, from JPA and JUnit, to JMeter and Android.
  • Each book comes as a standalone guide (with source code provided), so that you use it as reference.
Last Step ...

Where should we send the free eBooks?

Good Work!
To download the books, please verify your email address by following the instructions found on the email we just sent you.