Konstantina Dimtsa

About 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 try-catch. 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 two of our best selling eBooks for FREE!

JPA Mini Book

Learn how to leverage the power of JPA in order to create robust and flexible Java applications. With this Mini Book, you will get introduced to JPA and smoothly transition to more advanced concepts.

JVM Troubleshooting Guide

The Java virtual machine is really the foundation of any Java EE platform. Learn how to master it with this advanced guide!

Given email address is already subscribed, thank you!
Oops. Something went wrong. Please try again later.
Please provide a valid email address.
Thank you, your sign-up request was successful! Please check your e-mail inbox.
Please complete the CAPTCHA.
Please fill in the required fields.
Examples Java Code Geeks and all content copyright © 2010-2014, Exelixis Media Ltd | Terms of Use | Privacy Policy | Contact
All trademarks and registered trademarks appearing on Examples Java Code Geeks are the property of their respective owners.
Java is a trademark or registered trademark of Oracle Corporation in the United States and other countries.
Examples Java Code Geeks is not connected to Oracle Corporation and is not sponsored by Oracle Corporation.
Do you want to know how to develop your skillset and become a ...
Java Rockstar?

Subscribe to our newsletter to start Rocking right now!

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

Get ready to Rock!
You can download the complementary eBooks using the links below:
Close