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

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 Java exception handler. The exception handling in Java is a mechanism to handle runtime errors so that the normal flow of the program can be maintained. An exception is an error that 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 of the 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 an exception handler. Also, the exception handler may optionally include the finally block.

Try Catch Java exceptions

1. Try – Catch – Finally Java 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 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

01
02
03
04
05
06
07
08
09
10
11
12
13
14
15
16
17
18
19
20
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 at 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:

01
02
03
04
05
06
07
08
09
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
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 on 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. Throw and Throws

In Java, we use throw and throws keywords as part of the Exception handling. As we have seen try with catch and try with finally blocks, in this section let us learn about these two keywords about their usage and requirement.

3.1 Throw

  • Sometimes we can create Exception Object explicitly and we can handover our created Exception object to the JVM manually. For this, we have to Use throw keyword.
  • In General, we can use throw Keyword for Customized Exceptions but not for pre-defined Exceptions.
  • After a throw statement, we are not allowed to write any statements directly otherwise we will get Compile Time Error unreachable statement.
  • We can use throw Keyword Only for Throwable Types. Otherwise, we will get Compile Time Error incompatible types.

Let us use the word programmatically to handle the user-defined or customized exception.CustomizedException.java

class TooYoungException extends RuntimeException {

	TooYoungException(String s) {  //constructor
	super(s);
	}
}


class TooOldException extends RuntimeException { 
		TooOldException(String s) { //constructor
		super(s);
    }
}


class CustomizedException {

	public static void main(String[] args) {

	int age = Integer.parseInt(args[0]);

	if(age > 60) 
	{
	throw new TooOldException("You are too old to get married.");
	}
	else if(age < 18) 
	{
	throw new TooYoungException("You are too young to get married");
	}
	else 
	{
	System.out.println("U will get Match Details Soon by Email...!");
	}
 }
}

if we input age which is below than 18 years old, the output is as follows:

Exception in thread "main" TooYoungException: You are too young to get married
        at CustomizedException.main(CustomizedException.java:28)

Similarly, if we input age which is greater than 60 years old, the output is as follows:

Exception in thread "main" TooOldException: You are too old to get married.
        at CustomizedException.main(CustomizedException.java:24)

3.2 Throws

In our program, if there is any chance of raising Checked Exception then Compulsory we should handle that Checked Exception. Otherwise, we will get Compile Time Error saying unreported exception XXX; must be caught or declared to be thrown.

We can Handle this Compile Time Error in 2 Ways.

  1. By using try-catch
  2. By using throws keyword

Already we have seen the first approach of try-catch in the previous sections. Now let us get into the second approach.

  • We can use throws keyword to delegate the responsibility of Exception Handling to the Caller Method (It Maybe another method OR JVM). Then Caller is responsible to handle that Checked Exception.
  • Throws keyword is required only for Checked Exceptions.
  • Using throws keyword for Unchecked Exceptions is of no use.
  • Throws keyword is required only to convince the compiler and it doesn’t prevent abnormal termination of the program.
  • Hence it is recommended to Use try- catch- finally, overthrows keyword.

Let us see an example in which we use both the approaches to handle the exception.

  1. By using try-catch
Example1.java
class Test {
public static void main(String args[]) {

	try {
    Thread.sleep(5000);
    }
    catch (InterruptedException e) {

     }
   }
}

2. By using throws keywordExample2.java

//using throws keyword in method declaration
class Test
{
	public static void main(String[] args) throws Exception {  

		Thread.sleep(5000);
	}
}

4. try-with-resources

Until 1.6 Java Version, it is highly recommended to write finally block to close all resources which are opened as part of a try block.

Problems in this approach are:

  • Compulsory Programmer is required to close all open resources in finally block. It increases the length of the code and reduces readability.
  • It increases the complexity of programming.

Consider the following code

import java.io.*;
class Test
{
	public static void main(String[] args) {
		BufferedReader br=null;
		try
		{
			br= new BufferedReader(new FileReader("input.txt"));  //opening resource
		}
		catch (Exception e)
		{
			//handling code
		}
		finally
		{
			br.close();   //explicitly closing the resource
		}
	}

}

We have explicitly written finally block and closed the resource. Same thing we can achieve using try-with-resources enhancement provided in java 1.7 version.

import java.io.*;
class TryWithResources 
{
public static void main (String args[]) throws Exception
 {
	try (BufferedReader br = new BufferedReader (new FileReader ("abc.txt"))) //try-with-resource
 	{ 
    //file related operations
 	}
	catch(Exception e)
	{
   //handling code
	}
 }               //finally block is removed
}  

We have totally removed finally block, and the resource BufferedReader which is declared along with try block is automatically closed after program execution.

5. Conclusion

As we stated at the beginning of this article, the exception handling in Java is a mechanism to handle runtime errors so that the normal flow of the program can be maintained.

In this article, we have started with try-catch and try-catch-finally blocks, then we looked into throws and throw keyword and its requirement as part of the Exception Handling in Java. Finally, we ended up our study looking into try-with-resources enhancement in Exception Handling.

7. Download the Source Code

This is an example of Try Catch in Java.

Download
You can download the full source code of this example here: Try Catch Java Example

Last updated on May 12th, 2021

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 ....

 

Receive Java & Developer job alerts in your Area

I have read and agree to the terms & conditions

 

Subscribe
Notify of
guest

This site uses Akismet to reduce spam. Learn how your comment data is processed.

0 Comments
Inline Feedbacks
View all comments