The Wayback Machine - https://web.archive.org/web/20241003162147/https://www.geeksforgeeks.org/try-catch-throw-and-throws-in-java/
Open In App

Java Try Catch Block

Last Updated : 26 Sep, 2023
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

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.



Previous Article
Next Article

Similar Reads

Flow control in try catch finally in Java
In this article, we'll explore all the possible combinations of try-catch-finally which may happen whenever an exception is raised and how the control flow occurs in each of the given cases. Control flow in try-catch clause OR try-catch-finally clause Case 1: Exception occurs in try block and handled in catch blockCase 2: Exception occurs in try-bl
6 min read
Java Multiple Catch Block
Before Java 7, we had to catch only one exception type in each catch block. So, whenever we needed to handle more than one specific exception but take some action for all exceptions, we had to have more than one catch block containing the same code. In the following code, we have to handle two different exceptions but take the same action for both.
3 min read
Try-with-resources Feature in Java
In Java, the Try-with-resources statement is a try statement that declares one or more resources in it. A resource is an object that must be closed once your program is done using it. For example, a File resource or a Socket connection resource. The try-with-resources statement ensures that each resource is closed at the end of the statement execut
4 min read
Automatic Resource Management in Java ( try with resource statements )
Java provides a feature to make the code more robust and to cut down the lines of code. This feature is known as Automatic Resource Management(ARM) using try-with-resources from Java 7 onwards. The try-with-resources statement is a try statement that declares one or more resources. This statement ensures that each resource is closed at the end of t
5 min read
Java SE 9 : Improved try-with-resources statements
In java 7 or 8 if a resource is already declared outside the try-with-resources statement, we should re-refer it with local variable. That means we have to declare a new variable in try block. Let us look at the code explaining above argument : // Java code illustrating try-with-resource import java.io.*; class Gfg { public static void main(String
2 min read
10 Most Popular Java Frameworks That You Must Try
In today's technology-driven world, we all can see how frequently tech advancements are coming into existence and subsequently how old tools & technologies are becoming obsolete and uncompetitive. But the case is not the same with every single technology as JAVA is one of those few technologies out there that has been enjoying a strong position
9 min read
Nested try blocks in Exception Handling in Java
In Java , we can use a try block within a try block. Each time a try statement is entered, the context of that exception is pushed onto a stack. Given below is an example of a nested try. In this example, the inner try block (or try-block2) is used to handle ArithmeticException, i.e., division by zero. After that, the outer try block (or try-block)
3 min read
Initialization of local variable in a conditional block in Java
Java comprises 5 conditional blocks namely - if, switch, while, for and try. In all these blocks, if the specified condition is true, the code inside the block is executed and vice-versa. Also, Java compiler doesn't let you leave a local variable uninitialized. While initializing local variable inside a conditional block, one must bear the followin
3 min read
Static Block and main() method in Java
In Java static block is used to initialize the static data members. Important point to note is that static block is executed before the main method at the time of class loading. This is illustrated well in the following example: // Java program to demonstrate that static // block is executed before main() class staticExample { // static block stati
2 min read
Block Lambda Expressions in Java
Lambda expression is an unnamed method that is not executed on its own. These expressions cause anonymous class. These lambda expressions are called closures. Lambda's body consists of a block of code. If it has only a single expression they are called "Expression Bodies". Lambdas which contain expression bodies are known as "Expression Lambdas". B
4 min read
Constructor Overloading with Static Block in Java
In Java, Constructor is a block of codes similar to the method that is used to initialize the object’s state. A constructor is invoked at the time of object or instance creation. Each time an object is created using a new() keyword at least one constructor (it could be default constructor) is invoked to assign initial values to the data members of
4 min read
Why You Need to Close the Java Streams in Finally Block?
In Java finally block is a block used to execute important and common code. The finally block is mostly used during exception handling with try and catch to close streams and files. The code in finally block is executed irrespective of whether there is an exception or not. This ensures that all the opened files are properly closed and all the runni
2 min read
How to Execute Instance Initialization Block (IIB) without Creating Object in Java?
In a Java program, operations can be performed on methods, constructors, and initialization blocks. Instance Initialization Blocks or IIB are used to initialize instance variables. We know that the instance block is the name-less method in java inside which we can define logic and they possess certain characteristics. Instance block logic is common
3 min read
The Initializer Block in Java
In order to perform any operations while assigning values to an instance data member, an initializer block is used. In simpler terms, the initializer block is used to declare/initialize the common part of various constructors of a class. It runs every time whenever the object is created. The initializer block contains the code that is always execut
2 min read
Instance Initialization Block (IIB) in Java
In a Java program, operations can be performed on methods, constructors, and initialization blocks. Instance Initialization Blocks or IIBs are used to initialize instance variables. So firstly, the constructor is invoked and the java compiler copies the instance initializer block in the constructor after the first statement super(). They run each t
3 min read
Method and Block Synchronization in Java
Threads communicate primarily by sharing access to fields and the objects reference fields refer to. This form of communication is extremely efficient, but makes two kinds of errors possible: thread interference and memory consistency errors. Some synchronization constructs are needed to prevent these errors. Following example shows a situation whe
7 min read
Difference Between java.sql.Time, java.sql.Timestamp and java.sql.Date in Java
Across the software projects, we are using java.sql.Time, java.sql.Timestamp and java.sql.Date in many instances. Whenever the java application interacts with the database, we should use these instead of java.util.Date. The reason is JDBC i.e. java database connectivity uses these to identify SQL Date and Timestamp. Here let us see the differences
7 min read
Java AWT vs Java Swing vs Java FX
Java's UI frameworks include Java AWT, Java Swing, and JavaFX. This plays a very important role in creating the user experience of Java applications. These frameworks provide a range of tools and components for creating graphical user interfaces (GUIs) that are not only functional but also visually appealing. As a Java developer, selecting the righ
11 min read
Java.io.ObjectInputStream Class in Java | Set 2
Java.io.ObjectInputStream Class in Java | Set 1 Note : Java codes mentioned in this article won't run on Online IDE as the file used in the code doesn't exists online. So, to verify the working of the codes, you can copy them to your System and can run it over there. More Methods of ObjectInputStream Class : defaultReadObject() : java.io.ObjectInpu
6 min read
Java.lang.Class class in Java | Set 1
Java provides a class with name Class in java.lang package. Instances of the class Class represent classes and interfaces in a running Java application. The primitive Java types (boolean, byte, char, short, int, long, float, and double), and the keyword void are also represented as Class objects. It has no public constructor. Class objects are cons
15+ min read
Java.lang.StrictMath class in Java | Set 2
Java.lang.StrictMath Class in Java | Set 1More methods of java.lang.StrictMath class 13. exp() : java.lang.StrictMath.exp(double arg) method returns the Euler’s number raised to the power of double argument. Important cases: Result is NaN, if argument is NaN.Result is +ve infinity, if the argument is +ve infinity.Result is +ve zero, if argument is
6 min read
java.lang.instrument.ClassDefinition Class in Java
This class is used to bind together the supplied class and class file bytes in a single ClassDefinition object. These class provide methods to extract information about the type of class and class file bytes of an object. This class is a subclass of java.lang.Object class. Class declaration: public final class ClassDefinition extends ObjectConstruc
2 min read
Java.util.TreeMap.pollFirstEntry() and pollLastEntry() in Java
Java.util.TreeMap also contains functions that support retrieval and deletion at both, high and low end of values and hence give a lot of flexibility in applicability and daily use. This function is poll() and has 2 variants discussed in this article. 1. pollFirstEntry() : It removes and retrieves a key-value pair with the least key value in the ma
4 min read
Java.util.TreeMap.floorEntry() and floorKey() in Java
Finding greatest number less than given value is used in many a places and having that feature in a map based container is always a plus. Java.util.TreeMap also offers this functionality using floor() function. There are 2 variants, both are discussed below. 1. floorEntry() : It returns a key-value mapping associated with the greatest key less than
3 min read
java.lang.Math.atan2() in Java
atan2() is an inbuilt method in Java that is used to return the theta component from the polar coordinate. The atan2() method returns a numeric value between -[Tex]\pi [/Tex]and [Tex]\pi [/Tex]representing the angle [Tex]\theta [/Tex]of a (x, y) point and the positive x-axis. It is the counterclockwise angle, measured in radian, between the positiv
1 min read
java.net.URLConnection Class in Java
URLConnection Class in Java is an abstract class that represents a connection of a resource as specified by the corresponding URL. It is imported by the java.net package. The URLConnection class is utilized for serving two different yet related purposes, Firstly it provides control on interaction with a server(especially an HTTP server) than URL cl
5 min read
Java 8 | ArrayDeque removeIf() method in Java with Examples
The removeIf() method of ArrayDeque is used to remove all those elements from ArrayDeque which satisfies a given predicate filter condition passed as a parameter to the method. This method returns true if some element are removed from the Vector. Java 8 has an important in-built functional interface which is Predicate. Predicate, or a condition che
3 min read
Java.util.GregorianCalendar Class in Java
Prerequisites : java.util.Locale, java.util.TimeZone, Calendar.get()GregorianCalendar is a concrete subclass(one which has implementation of all of its inherited members either from interface or abstract class) of a Calendar that implements the most widely used Gregorian Calendar with which we are familiar. java.util.GregorianCalendar vs java.util.
10 min read
Java lang.Long.lowestOneBit() method in Java with Examples
java.lang.Long.lowestOneBit() is a built-in method in Java which first convert the number to Binary, then it looks for first set bit present at the lowest position then it reset rest of the bits and then returns the value. In simple language, if the binary expression of a number contains a minimum of a single set bit, it returns 2^(first set bit po
3 min read
Java Swing | Translucent and shaped Window in Java
Java provides different functions by which we can control the translucency of the window or the frame. To control the opacity of the frame must not be decorated. Opacity of a frame is the measure of the translucency of the frame or component. In Java, we can create shaped windows by two ways first by using the AWTUtilities which is a part of com.su
5 min read
Article Tags :
Practice Tags :