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

Related Whitepaper:

Java Essential Training

Author David Gassner explores Java SE (Standard Edition), the language used to build mobile apps for Android devices, enterprise server applications, and more!

The course demonstrates how to install both Java and the Eclipse IDE and dives into the particulars of programming. The course also explains the fundamentals of Java, from creating simple variables, assigning values, and declaring methods to working with strings, arrays, and subclasses; reading and writing to text files; and implementing object oriented programming concepts. Exercise files are included with the course.

Get it Now!  

Examples Java Code Geeks and all content copyright © 2010-2014, Exelixis Media Ltd | Terms of Use | Privacy Policy
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.

Sign up for our Newsletter

20,709 insiders are already enjoying weekly updates and complimentary whitepapers! Join them now to gain exclusive access to the latest news in the Java world, as well as insights about Android, Scala, Groovy and other related technologies.

As an extra bonus, by joining you will get our brand new e-books, published by Java Code Geeks and their JCG partners for your reading pleasure! Enter your info and stay on top of things,

  • Fresh trends
  • Cases and examples
  • Research and insights
  • Two complimentary e-books