BeginnersBook

  • Home
  • Java
    • Java OOPs
    • Java Collections
    • Java Examples
  • C
    • C Examples
  • C++
    • C++ Examples
  • DBMS
  • Computer Network
  • Python
    • Python Examples
  • More…
    • jQuery
    • Kotlin
    • WordPress
    • SEO
    • JSON
    • JSP
    • JSTL
    • Servlet
    • MongoDB
    • XML
    • Perl

Try Catch in Java – Exception handling

Last Updated: May 30, 2024 by Chaitanya Singh | Filed Under: java

Try catch block is used for exception handling in Java. The code (or set of statements) that can throw an exception is placed inside try block and if the exception is raised, it is handled by the corresponding catch block. In this guide, we will see various examples to understand how to use try-catch for exception handling in java.

Try block in Java

As mentioned in the beginning, try block contains set of statements where an exception can occur. A try block is always followed by a catch block or finally block, if exception occurs, the rest of the statements in the try block are skipped and the flow immediately jumps to the corresponding catch block.

Note: A try block must be followed by catch blocks or finally block or both.

Syntax of try block with catch block

try{
   //statements that may cause an exception
}catch(Exception e){
  //statements that will execute when exception occurs
}    

Syntax of try block with finally block

try{
   //statements that may cause an exception
}finally{
  //statements that execute whether the exception occurs or not
}    

Syntax of try-catch-finally in Java

try{
   //statements that may cause an exception
}catch(Exception e){
  //statements that will execute if exception occurs
}finally{
  //statements that execute whether the exception occurs or not
}    

Note: It is upto the programmer to choose which statements needs to be placed inside try block. If programmer thinks that certain statements in a program can throw a exception, such statements can be enclosed inside try block and potential exceptions can be handled in catch blocks.

Catch block in Java

A catch block is where you handle the exceptions, this block must immediately placed after a try block. A single try block can have several catch blocks associated with it.

You can catch different exceptions in different catch blocks. When an exception occurs in try block, the corresponding catch block that handles that particular exception executes. For example if an arithmetic exception occurs in try block then the statements enclosed in catch block for arithmetic exception executes.

Syntax of try catch in java

try
{
     //statements that may cause an exception
}
catch (exception(type) e(object))‏
{
     //error handling code
}

Example: try catch in Java

If an exception occurs in try block then the control of execution is passed to the corresponding catch block. As discussed earlier, a single try block can have multiple catch blocks associated with it, you should place the catch blocks in such a way that the generic exception handler catch block is at the last(see in the example below).

The generic exception handler can handle all the exceptions but you should place is at the end, if you place it at the before all the catch blocks then it will display the generic message. You always want to give the user a meaningful message for each type of exception rather then a generic message.

class Example1 {
   public static void main(String args[]) {
      int num1, num2;
      try {
         /* We suspect that this block of statement can throw 
          * exception so we handled it by placing these statements
          * inside try and handled the exception in catch block
          */
         num1 = 0;
         num2 = 62 / num1;
         System.out.println(num2);
         System.out.println("Hey I'm at the end of try block");
      }
      catch (ArithmeticException e) { 
         /* This block will only execute if any Arithmetic exception 
          * occurs in try block
          */
         System.out.println("You should not divide a number by zero");
      }
      catch (Exception e) {
         /* This is a generic Exception handler which means it can handle
          * all the exceptions. This will execute if the exception is not
          * handled by previous catch blocks.
          */
         System.out.println("Exception occurred");
      }
      System.out.println("I'm out of try-catch block in Java.");
   }
}

Output:

You should not divide a number by zero
I'm out of try-catch block in Java.

Multiple catch blocks in Java

The example we seen above is having multiple catch blocks, let’s see few rules about multiple catch blocks with the help of examples. To read this in detail, see catching multiple exceptions in java.

1. As I mentioned above, a single try block can have any number of catch blocks.

2. A generic catch block can handle all the exceptions. Whether it is ArrayIndexOutOfBoundsException or ArithmeticException or NullPointerException or any other type of exception, this handles all of them. To see the examples of NullPointerException and ArrayIndexOutOfBoundsException, refer this article: Exception Handling example programs.

catch(Exception e){
  //This catch block catches all the exceptions
}

If you are wondering why we need other catch handlers when we have a generic that can handle all. This is because in generic exception handler you can display a message but you are not sure for which type of exception it may trigger so it will display the same message for all the exceptions and user may not be able to understand which exception occurred. Thats the reason you should place is at the end of all the specific exception catch blocks

3. If no exception occurs in try block then the catch blocks are completely ignored.

4. Corresponding catch blocks execute for that specific type of exception:
catch(ArithmeticException e) is a catch block that can handle ArithmeticException
catch(NullPointerException e) is a catch block that can handle NullPointerException

try catch block in java

5. You can also throw exception, which is an advanced topic and I have covered it in separate tutorials: user defined exception, throws keyword, throw vs throws.

Example of Multiple catch blocks

class Example2{
   public static void main(String args[]){
     try{
         int a[]=new int[7];
         a[4]=30/0;
         System.out.println("First print statement in try block");
     }
     catch(ArithmeticException e){
        System.out.println("Warning: ArithmeticException");
     }
     catch(ArrayIndexOutOfBoundsException e){
        System.out.println("Warning: ArrayIndexOutOfBoundsException");
     }
     catch(Exception e){
        System.out.println("Warning: Some Other exception");
     }
   System.out.println("Out of try-catch block...");
  }
}

Output:

Warning: ArithmeticException
Out of try-catch block...

In the above example there are multiple catch blocks and these catch blocks executes sequentially when an exception occurs in try block. Which means if you put the last catch block ( catch(Exception e)) at the first place, just after try block then in case of any exception this block will execute as it can handle all exceptions. This catch block should be placed at the last to avoid such situations.

Finally block

A finally block contains a block of code that always executes regardless of whether an exception occurs or not. See the snippet below. I have covered this in a separate tutorial here: java finally block.

try {
// Code that may throw an exception
} catch (ExceptionType1 e1) {
// Handle exception of type ExceptionType1
} catch (ExceptionType2 e2) {
// Handle exception of type ExceptionType2
} finally {
// Code that will always execute
}
❮ PreviousNext ❯

Top Related Articles:

  1. Nested try catch block in Java – Exception handling
  2. Exception handling in Java with examples
  3. Constructor Overloading in Java with examples
  4. Interface in java with example programs
  5. What is case Keyword in Java

Tags: Exception-Handling

About the Author

I have 15 years of experience in the IT industry, working with renowned multinational corporations. Additionally, I have dedicated over a decade to teaching, allowing me to refine my skills in delivering information in a simple and easily understandable manner.

– Chaitanya

Comments

  1. rajeev says

    November 18, 2014 at 8:19 AM

    How to determine which will be better to handle exception all of the these below:
    try catch,throw,throws.
    If we can handle all type of exception using try catch then why we need throw or throws

    Reply
    • Naveen says

      October 9, 2015 at 2:25 PM

      Try-Catch is the best to handle exceptions

      throws is only for compiletime exceptions

      throw cluase is usefull if you want to throw new exception which are not mentioned in java.lang package

      Reply
    • Kalyan Reddy says

      March 4, 2017 at 9:31 AM

      1. try..catch is to handle the exception at that place itself. Hence, program continues once the associated catch block code is executed. If not caught with associated, it looks for outer try..catch blocks. here, the code following try block will not be executed unless (only finally block is executed). This process continues until this is handled by some catch block and the last option is Java Run time handle, where it prints exception stack.
      2. Throws is where you expect some exceptions ( checked or unchecked), but not interested in handling them. So, when exception occurs, it looks for handler in outer try block or in calling method.
      3. Throw – is used when User wants to through manually than the system. Suppose, Divide by zero can be caught by system or with try ..catch. In case, yourself want to verify the values of the divider for zero and then can throw your own or already defined exceptions with Throw.
      Correct me, if I anything is missing.

      Reply
  2. Pawan says

    March 15, 2015 at 6:05 PM

    what does the rest of code which placed out of catch block.
    And what will happen, if finally block will use in nested try?

    Reply
  3. abhishek says

    June 7, 2015 at 11:58 AM

    when in catch block there is one class “exception”which includes all the exception types then why we use multiple catches block..?

    Reply
    • Rohith says

      January 9, 2017 at 7:49 PM

      It’s because if you want to catch a specific exception and may even write some statements in the block specific to that exception. You can do that with Exception class too. But, you won’t be able to identify the problem easily.
      “Exception” is the parent class and will be used to catch mostly generic or unexpected exceptions.

      Reply
  4. Vinay R says

    November 1, 2015 at 5:04 PM

    If we write 2 exception in the same try block ex arithmetic exception and array index out of exception and the corresponding catch blocks then the output we ll get only arithmetic exception. why it is not handling array index out of bounds exception. please tell me….

    Thanks in advance.

    T

    Reply
    • Puennendu Paul says

      April 23, 2016 at 6:13 AM

      because ArithmeticException is done before ArrayIndexOutOfBoundsException. You will see that, after arithmetic operation is done the result will assigned to the array.

      Reply
      • nikunj ramani says

        September 4, 2016 at 1:23 PM

        if first exception is genereted then execute corresponding catch block & second exception is ignore…u can try alternate exception…

        Reply
  5. Nimmy says

    January 19, 2016 at 12:29 PM

    very nice and Simple article. good work!!

    Reply
  6. Birampal singh says

    February 15, 2016 at 10:17 AM

    Q1. how many try in one java program?
    Q2. how many catch in one java program?
    Q3. how many finally in one java program?

    thanks

    Reply
    • Purnendu Paul says

      April 23, 2016 at 6:15 AM

      Ans. of Q2.: More than one catch can be used under a try.

      Reply
  7. Nawal Sah says

    February 17, 2016 at 6:56 AM

    What is the parameter datatype of catch block?

    Reply
  8. Abhinabo says

    February 23, 2016 at 6:35 PM

    What if there is an error/exception in the catch block?

    Reply
    • Shaun says

      March 18, 2016 at 2:11 PM

      you should know if the catch block needed another try catch nessted. best way to avoid this would be to validate all data first anyway.

      eg.

      If(userInputVariable == 0) {
      System.out.println(“You cannont divide by 0)
      return
      }

      This would be better than using a try catch block.
      use them as little as possible

      Reply
  9. Chandu says

    April 19, 2016 at 4:24 AM

    Why we declare throws at method level signature?

    Reply
  10. atul says

    April 20, 2016 at 6:25 AM

    a catch clause may catch exceptions of which type justification
    a:error
    b:throwable
    c:exception
    d:string

    Reply
  11. Purnendu Paul says

    April 23, 2016 at 6:07 AM

    catch(Exception e){}
    is not working at all. After compilation it shows——
    “incompatible types: Exception cannot be converted to Throwable”

    What should I do?

    Reply
  12. Ranjitha says

    July 4, 2016 at 4:13 PM

    Suppose if a try block has divide by zero exception …and we have two catch blocks like one is exception which covers all exception and another one is specific arithmetic exception…for this statement under which catch block will get print…either exception or arithmetic exception…
    Thanks in advance…

    Reply
    • Rajat says

      February 7, 2017 at 3:01 AM

      If you place Exception catch block first, then the other block(Arithmetic Exception one) will become unreachable and it will show this error “Unreachable catch block for ArithmeticException. It is already handled by the catch block for Exception”.

      If you place arithmetic exception catch block first, then it will get executed smoothly without any issue.

      Reply
  13. vijay says

    August 23, 2016 at 5:34 PM

    I have one dought… In catch block already catch(exception e)..is there then why we go for
    catch( arthemeticexception e)…..why we write the extra airthrmatic block….exception block is sufficient for that…

    Reply
    • Shilpa says

      July 10, 2017 at 9:38 AM

      if you put the last catch block ( catch(Exception e)) at the first place, just after try block then in case of any exception this block will execute as it has theability to handle all exceptions. This catch block should be placed at the last to avoid such situations.
      It’s because if you want to catch a specific exception and may even write some statements in the block specific to that exception. You can do that with Exception class too. But, you won’t be able to identify the problem easily.
      “Exception” is the parent class and will be used to catch mostly generic or unexpected exceptions.

      Reply
  14. nikunj ramani says

    September 4, 2016 at 1:21 PM

    can we define more than 1 try block in same class?????

    Reply
    • Rohith says

      January 9, 2017 at 7:53 PM

      Yes. You can declare as many try blocks as you want. Just that each of them should have a catch or finally or both.
      They are all independent to each other and there can be multiple catch blocks for each of those “try” blocks.

      Reply
  15. rash says

    October 28, 2016 at 5:55 AM

    when in catch block there is one class “exception”which includes all the exception types then why we use multiple catches block..?

    Reply
    • Abhishek Wadhwa says

      January 11, 2017 at 3:43 PM

      We use multiple catch block to take actions according to specific exception, Example: You might want to ignore ArithmeticException so you will write
      catch(ArithmeticException e){
      //Do nothing
      }
      Now you want to take some action when there is ArrayIndexOutOfBoundsException so you will write
      catch(ArrayIndexOutOfBoundsException e){
      Log(“Index out of Bound Exception occur, look at the code”);
      }

      Reply
  16. widyasaagar says

    December 7, 2016 at 3:53 PM

    how many try blocks can be used under single class in a program

    Reply
  17. shakir says

    February 21, 2017 at 12:46 PM

    Here we are using catch block…what is the need and use of using finally block?

    Reply
  18. lavanya says

    February 28, 2017 at 6:24 AM

    In the example multiple catch blocks in java, the size of array is 7 right…………………………. int a[]=new int[7];
    a[4]=30/0;
    a[4] means it is referring to index 4…..but why it is showing ArrayIndexOutOfBoundsException

    Reply

Leave a Reply Cancel reply

Your email address will not be published. Required fields are marked *

Java Tutorial

Java Introduction

  • Java Index
  • Java Introduction
  • History of Java
  • Features of Java
  • C++ vs Java
  • JDK vs JRE vs JVM
  • JVM - Java Virtual Machine
  • First Java Program
  • Variables
  • Data Types
  • Operators

Java Flow Control

  • Java If-else
  • Java Switch-Case
  • Java For loop
  • Java while loop
  • Java do-while loop
  • Continue statement
  • break statement

Java Arrays

  • Java Arrays

OOPs Concepts

  • OOPs Concepts
  • Constructor
  • Java String
  • Static keyword
  • Inheritance
  • Types of inheritance
  • Aggregation
  • Association
  • Super Keyword
  • Method overloading
  • Method overriding
  • Overloading vs Overriding
  • Polymorphism
  • Types of polymorphism
  • Static and dynamic binding
  • Abstract class and methods
  • Interface
  • Abstract class vs interface
  • Encapsulation
  • Packages
  • Access modifiers
  • Garbage Collection
  • Inner classes
  • Static import
  • Static constructor

Java Exception Handling

  • Exception handling
  • Java try-catch
  • Java throw
  • Java throws
  • Checked and Unchecked Exceptions
  • Jav try catch finally
  • Exception Examples
  • Exception Propagation

Collections Framework

  • Collections in Java
  • Java ArrayList
  • Java LinkedList
  • Java Vector
  • Java HashSet
  • Java LinkedHashSet
  • Java TreeSet
  • Java HashMap
  • Java TreeMap
  • Java LinkedHashMap
  • Java Queue
  • Java PriorityQueue
  • Java Deque
  • Comparable interface
  • Comparator interface
  • Collections Interview Questions

MORE ...

  • Java Scanner Class
  • Java 8 Features
  • Java 9 Features
  • Java Conversion
  • Java Date
  • Java Multithreading
  • Java I/O
  • Java Serialization
  • Java Regex
  • Java AWT
  • Java Swing
  • Java Enum
  • Java Annotations
  • Java main method
  • Java Interview Q

Copyright © 2012 – 2025 BeginnersBook . Privacy Policy . Sitemap