Try Catch in Java Explained [Exception Handling Examples]


Written By - Bashir Alam

 

Advertisement

Introduction to try catch exception handling in Java

Errors occur frequently while coding in any programming language. Sometimes, we may misspell a name or keyword, or sometimes we unknowingly change the symbols. These are very common and easy to handle errors. But there are some errors that are not that much easy to handle, we need a special block of codes to handle such complex errors.

In this tutorial, we will learn how we can handle different errors and exceptions in java programming using the try catch java block method. We will first learn the basic syntax of the java try and catch method and will solve some of the exceptions by taking various examples. Moreover, we will also cover different types of exceptions and errors that are common in a java programming language.

Towards the end of this tutorial, we will also learn about throw and finally keywords and see how they are useful in handling exceptions. In a nutshell, this tutorial is going to have all the details about the java try and catch block method to handle errors and exceptions.

 

Getting started with try catch Java method

When an error or exception occurs, the java program stops execution further. So in order to continue the execution we have to solve the errors and exceptions by using different java error and exception handling methods. Before going into the details of error and exception handling in java, let us first understand what an error and exception are? In this section, we will define errors and exceptions and their different types in java.

 

Different Java Error Types

In Java, an error is a subclass of Throwable that tells that something serious problem is existing and a reasonable Java application should not try to catch that error.  As these errors are abnormal conditions and should not occur, thus, error and its subclass are referred to as Unchecked Exceptions. Basically, there are two types of java errors which are listed below:

  • Compile-time errors: Compile-time errors are the errors resulting from a violation of programming language’s grammar rules, for example writing syntactically incorrect statements. See the example of java compile-time error below:

Try Catch in Java Explained [Exception Handling Examples]

 

  • Run-time errors: Runtime errors occur during runtime or execution of the program because of unexpected situations. Some of the common run-time errors include zero division, invalid input, accessing the array beyond the range and etc. We use the exception handling method of Java to handle such errors. See the example below which gives run-time error when divided by zero.

// class
public class Main  { 
    public static void main(String[] args){
        System.out.println(6/0);
    }
}

Output:

Exception in thread "main" java.lang.ArithmeticException: / by zero
at Main.main(Main.java:4)

 

Different Java Exception Types

Exception in Java is an event that interrupts the execution of program instructions and disturbs the normal flow of program execution. It is an object that wraps an error event information that occurred within a method and it is passed to the runtime system. There are two types of java exceptions which are listed below:

Advertisement
  • Checked Exceptions: Checked Exceptions are also called compile-time exceptions because they occur at the compile time. If the method contains the code that throws a checked exception, the programmer must provide a mechanism to catch it in the same method. An example of a checked exception can be SQLException.

  • Unchecked Exceptions: Java Unchecked Exceptions are also called Runtime Exceptions because they occur at runtime. This occurs during the execution of the program. It totally depends upon the developer to catch the runtime or unchecked exceptions. The examples are ArithmeticException, NullPointerException, etc.

 

Exception handling in Java programming language

Exception handling is a transparent way to handle program errors.  It helps us to separate the error-handling code from the normal code and enhances readability. In this section, we will have a close look at the java exception handling method and will see how we can use the java try and catch method along with various examples.

 

The Syntax of Java try block

The try block in Java contains the statements where there is a chance of exception. A catch block always follows the try block. The simple syntax of java try blocks looks like this;

try{
    // statements
}

It is always recommended to use java try block if you think that certain statements in a program can throw an exception. A try block is always followed by a catch block.

 

The syntax of Java catch block

A catch block is a block where we can handle the exceptions. The catch block must always follow the try block. There can be multiple catch blocks in a try block. The simple syntax looks like this;

catch(expectionType){
    // statements
}

So, now the syntax of the java try and catch method looks like this;

// try catch java blocks
try{
    //statements
}
catch(exceptionType){
    // statements
}

Now let us take an example and see how we can handle an error using the java try and catch method.

Advertisement

Example-1: Handle error using try catch Java method

In this section, we will take an example of zero division error and handle it using the java try and catch blocks. See the program below:

// class
public class Main  { 
    public static void main(String[] args){
        // try catch java blocks
        // try block
        try{
            // zero division
            System.out.println(6/0);
        }
        // catch block
        catch(Exception e){
            // giving out message
            System.out.println("Zero division error");
        }
        
    }
}

Output:

Zero division error

Notice that we were able to catch the error and handle it without getting terminated from the program.

 

Example-2: Handle error using multiple try catch Java blocks

In some cases, we might want to know what kind of error occurs in the try block. In such cases, we can use multiple catch blocks with different possible exceptions. See the example below which uses multiple java try and catch blocks.

// class
public class Main  { 
    public static void main(String[] args){
        // try catch java blocks
        // try block
        try{
            // zero division
            System.out.println(6/0);
        }
        // catch block
        catch(ArithmeticException e){
            // giving out message
            System.out.println("Zero division error");
        }
        // catch block
        catch(ArrayIndexOutOfBoundsException e){
            System.out.println("Index out of range!!");
        }
        
    }
}

Output:

Zero division error

Notice that we had specified the type of exception inside the round brackets in the catch block. So, when an error occurs in the try block, then depending on the type of exception the catch block will execute. See the example below which tries to print an element that does not exist in an array.

Advertisement
// class
public class Main  { 
    public static void main(String[] args){
        // java array
        int arr[] = {1, 2, 3, 4};
        // try catch java blocks
        // try block
        try{
            // printing element
            System.out.println(arr[5]);
        }
        // catch block
        catch(ArithmeticException e){
            // giving out message
            System.out.println("Zero division error");
        }
        // catch block
        catch(ArrayIndexOutOfBoundsException e){
            System.out.println("Index out of range!!");
        }
        
    }
}

Output:

Index out of range!!

Notice that when we tried to print the element which does not exist we get an "array index out of range" error and accordingly the catch block was executed.

 

Example-3: Printing the Java exception

We already have learned how we can handle an exception using the java try and catch block. In some cases, we might also want to print out the error to display to the user. We can do that by printing the error as it is. See the example below:

// class
public class Main  { 
    public static void main(String[] args){
        // java array
        int arr[] = {1, 2, 3, 4};
        // try catch java blocks
        // try block
        try{
            // printing element
            System.out.println(arr[5]);
        }
        // catch block
        catch(Exception e){
            // printing the exception
            System.out.println("The execption is: \n"+e);
        }
        
    }
}

Output:

The execption is:
java.lang.ArrayIndexOutOfBoundsException: Index 5 out of bounds for length 4

Notice that we were able to print out the type of exception without knowing it. Now, let us take one more example and print out the exception. See the example below:

// class
public class Main  { 
    public static void main(String[] args){
        //try catch java blocks
        // try block
        try{
            // printing element
            System.out.println(6/0);
        }
        // catch block
        catch(Exception e){
            // printing the exception
            System.out.println("The execption is: \n"+e);
        }
        
    }
}

Output:

The execption is:
java.lang.ArithmeticException: / by zero

Notice that we are able to get the exception type by simply printing it.

 

More about Java exception handling

Apart from the try and catch block, we can also use java throws and finally keywords to handle java exceptions and errors as well. In this section, we will see how we can use throws and finally blocks in java exception handling by taking various examples.

 

Throw keyword and Java exception handling

The throws is a keyword used to indicate that this method can throw a specified type of exception. The caller has to handle the exception using a try-catch block or propagate the exception. We can throw either checked or unchecked exceptions using the throws keyword. With the help of the throws keyword, we can provide information to the caller of the method about the types of exceptions the method might throw. The simple syntax looks like this;

MethodName(parameter) throws exception

Now let us take an example and see how it actually works. First, let us have a look at the example without using the throws keyword. See the example below:

Advertisement
// class
public class Main  { 
    public static void main(String[] args)
    {
        Thread.sleep(100);
        System.out.println("Print successfully");
    }
}

Output:

Try Catch in Java Explained [Exception Handling Examples]

In the above program, we are getting the compile-time error because there is a chance of an exception if the main thread is going to sleep. Now let us use the throws keyword to handle the above-given error. See the example below:

// class
public class Main  { 
    public static void main(String[] args)throws InterruptedException
    {
        Thread.sleep(100);
        System.out.println("Print successfully");
    }
}

Output:

Print successfully

 

Finally keyword in Java exception handling

The finally keyword in java is used to put important codes such as clean up code e.g. closing the file or closing the connection. The finally block executes whether exception rise or not and whether exception is handled or not. A finally contains all the crucial statements regardless of the exception occurs or not. The simple syntax looks like this;

finally{
    // important statements
}

Now let us use the finally block along with try catch java block. See the example below:

// class
public class Main  { 
    public static void main(String[] args)
    // try catch java blocks
    {
        // try block
        try{
            System.out.println(9/3);
        }
        // catch
        catch (Exception e){
            System.out.println("Exception occurs");
        }
        // finally
        finally{
            System.out.println("successfully executed!");
        }
    }
}

Output:

3
successfully executed!

Notice that there was no error and the finally block was executed. Now let us take an example of having an execption with finally keyword. See the example below:

// class
public class Main  { 
    public static void main(String[] args)
    // try catch java blocks
    {
        // try block
        try{
            System.out.println(9/0);
        }
        // catch
        catch (Exception e){
            System.out.println("Exception occurs");
        }
        // finally
        finally{
            System.out.println("successfully executed!");
        }
    }
}

Output:

Exception occurs
successfully executed!

Notice that the finally block was still executed after handling an exception as well. We can conclude that the finally block will be executed with or without having exceptions.

 

Summary

While writing code, we may come across various different kinds of errors and exception and the best way is to handle those exceptions using build in error and exception handling methods. In this tutorial, we learned about try catch java method to handle java exceptions. We first covered different kinds of exceptions that might occur in our program and then solve various examples to handle exceptions using the java try and catch block method.

Advertisement

Moreover, we also learned about the usage of throws and finally keyword in exception handling. All in all, this tutorial is one of the informative tutorials about java try and catch blocks and exception handling.

 

Further Reading

Try  block
catch blocks
exception handling in java

 

Didn't find what you were looking for? Perform a quick search across GoLinuxCloud

If my articles on GoLinuxCloud has helped you, kindly consider buying me a coffee as a token of appreciation.

Buy GoLinuxCloud a Coffee

For any other feedbacks or questions you can either use the comments section or contact me form.

Thank You for your support!!

Leave a Comment