Open In App

Java Try Catch Block

Improve
Improve
Like Article
Like
Save
Share
Report

In Java exception is an “unwanted or unexpected event”, that occurs during the execution of the program. When an exception occurs, the execution of the program gets terminated. To avoid these termination conditions we can use try catch block in Java. In this article, we will learn about Try, catch, throw, and throws in Java.

Why Does an Exception occur? 

An exception can occur due to several reasons like a Network connection problem, Bad input provided by a user, Opening a non-existing file in your program, etc 

Blocks and Keywords Used For Exception Handling 

1. try in Java

The try block contains a set of statements where an exception can occur.

try
{
// statement(s) that might cause exception
}

2. catch in Java

The catch block is used to handle the uncertain condition of a try block. A try block is always followed by a catch block, which handles the exception that occurs in the associated try block.

catch
{
// statement(s) that handle an exception
// examples, closing a connection, closing
// file, exiting the process after writing
// details to a log file.
}

3. throw in Java

The throw keyword is used to transfer control from the try block to the catch block. 

Below is the implementation of the above approach:

Java




// Java program that demonstrates the use of throw
class ThrowExcep {
    static void help()
    {
        try {
            throw new NullPointerException("error_unknown");
        }
        catch (NullPointerException e) {
            System.out.println("Caught inside help().");
            // rethrowing the exception
            throw e;
        }
    }
 
    public static void main(String args[])
    {
        try {
            help();
        }
        catch (NullPointerException e) {
            System.out.println(
                "Caught in main error name given below:");
            System.out.println(e);
        }
    }
}


Output

Caught inside help().
Caught in main error name given below:
java.lang.NullPointerException: error_unknown

4. throws in Java

The throws keyword is used for exception handling without try & catch block. It specifies the exceptions that a method can throw to the caller and does not handle itself. 

Below is the implementation of the above approach:

Java




// Java program to demonstrate working of throws
class ThrowsExecp {
 
    // This method throws an exception
    // to be handled
    // by caller or caller
    // of caller and so on.
    static void fun() throws IllegalAccessException
    {
        System.out.println("Inside fun(). ");
        throw new IllegalAccessException("demo");
    }
 
    // This is a caller function
    public static void main(String args[])
    {
        try {
            fun();
        }
        catch (IllegalAccessException e) {
            System.out.println("caught in main.");
        }
    }
}


Output

Inside fun(). 
caught in main.

5. finally in Java

It is executed after the catch block. We use it to put some common code (to be executed irrespective of whether an exception has occurred or not ) when there are multiple catch blocks. 

An example of an exception generated by the system is given below:

Exception in thread "main" 
java.lang.ArithmeticException: divide
by zero at ExceptionDemo.main(ExceptionDemo.java:5)
ExceptionDemo: The class name
main:The method name
ExceptionDemo.java:The file name
java:5:line number

Below is the implementation of the above approach:

Java




// Java program to demonstrate working of try,
// catch and finally
 
class Division {
    public static void main(String[] args)
    {
        int a = 10, b = 5, c = 5, result;
        try {
            result = a / (b - c);
            System.out.println("result" + result);
        }
 
        catch (ArithmeticException e) {
            System.out.println("Exception caught:Division by zero");
        }
 
        finally {
            System.out.println("I am in final block");
        }
    }
}


Output

Exception caught:Division by zero
I am in final block

FAQs For Try Block in Java

1. When should you use try catch blocks?

Try catch blocks are used to avoid exceptions so that code doesn’t break before the full execution.

2. What is throw and throws in Java?

The throw is used for transferring control from the try block to the catch block. Whereas throws is used for exception handling without try & catch block. Throws specify the exceptions that a method can throw to the caller and does not handle itself.

3. Can we have two catch blocks?

Yes, we can have multiple catch blocks with try statements.



Last Updated : 26 Sep, 2023
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads