Java try catch

java try catch

Java try catch


Exception is an event which may terminate the application at run time. The process of handling error is commonly known as “Exception Handling”. In this tutorial, we will discuss how we can handle different types of exceptions in java. We will create some basic examples to practice exception handling.


java try catch




Let’s discuss about try catch block in java first.


Try Catch Block


In Java, Try-Catch block is used to handle exceptions at run time. Those are reserved keywords.

We write block of code which can through exception or can fail at run time inside try block. And if any exception occurs at run time, catch block will access the exception object to display error information to the user.

Try catch block can be used only inside methods, you can not use it directly inside class area.

Basic Syntax of try catch block.

try {
    // Code Block
} catch (ExceptionClass obj) {
    // Catch Exception and print message
} finally {
    // Finally block can also be used
}

Some important things to know about try catch and finally


Before we write some examples and practice try catch, we need to know some basic things about try, catch and finally block. So, let’s discuss them.

  1. The try catch are reserved keywords in java and used to catch run time exceptions.
  2. You can use either finally or catch block after try block. But try block is must to have.
  3. Finally is a block which is always executed whether you have exception or not.
  4. You can also use multiple try catch block at the same time.
  5. You can have any number of catch block in your program.
  6. You can also have nested try catch block in your method.
  7. If you are using multiple try catch block then it is necessary to follow the hierarchy of exception class. Child class should come first before parent class from top to bottom.

An example on try catch block


Let’s create a basic example to understand how try catch block works. 

public class ExceptionDemo {

    public static void main(String arg[]) {

       System.out.println("Before exception.");
       try {

          int a = 10;

          System.out.println("Result : " + (a/0));

       } catch (Exception e) {
          System.out.println("Exception : " + e.getMessage());
       }
       System.out.println("Exception occurred and handled properly.");

    }

}

Output :
Before exception.
Exception : / by zero
Exception occurred and handled properly.

As you can see above, we are trying to divide a number by zero which will generate a run time exception. If we don’t handle this block of code, it will stop the execution of the program.

So we enclosed this block of code inside the try statement. When exception will occur, an exception object will be generated and will be passed to the run time machine. Run time machine will look for the appropriate handler for this exception object.

So it will find the Exception class which is the root of all the exception and error class. So run time system will pass exception object to the handler and catch statement will catch the exception object.

After that, you can get the detailed information of the exception.

Let’s see some important methods which you can use to get the detailed information of the particular exception occurred in your application at  run time.

Important Methods


Return Type Method name and detail
Throwable getCause()
Returns the cause of this throwable or null if the cause is nonexistent or unknown.
String getMessage()
Returns the detail message string of this throwable.
StackTraceElement[] getStackTrace()
Provides programmatic access to the stack trace information printed by printStackTrace().
void printStackTrace()
Prints this throwable and its backtrace to the standard error stream.
String toString()
Returns a short description of this throwable.


An example on multiple catch block in try catch block


As we have already discussed that we can also include multiple catch blocks with single try block. Let’s see how we can use it.

public class ExceptionDemo {

    public static void main(String arg[]) {

       System.out.println("Before exception.");
       try {

          int a = 10;

          System.out.println("Result : " + (a/0));

       } catch (ArithmeticException are) {
          System.out.println("Exception from ArithmeticExcpetion class : " + are.getMessage());
       } catch (Exception e) {
          System.out.println("Exception from Exception class : " e.getMessage());
       }
       System.out.println("Exception occurred and handled properly.");

    }

}

Output :
Before exception.
Exception from ArithmeticException class : / by zero
Exception occurred and handled properly.


as Look at the above example, we can include multiple catch block with single try block. But one important thing to remember here is, you need to maintain exception call hierarchy.

From top to bottom, first child class exception should come and after that it’s parent class. Run time system will look for the handler from top to bottom and once appropriate handler is found, rest of the handlers will be neglected.

Related Post

Leave a Reply

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