Java Exception Handling Tutorial

Exception Handling in Java Tutorial with Example Programs

Exceptions in Java - What are Java Exceptions?

A Java Exception is an abnormal condition that arises during the execution of a program and also called a run-time error. An exception in Java signals the unusual or catastrophic situations that can arise.
Examples of Java Exceptions are:
  • Incorrect user input such as division by zero
  • File that needs to be opened not found
  • Network connection problem

Types of Java Exceptions

Like anything else in this world, Exceptions can also be categorized! Based on whether or not you are required to handle the exception, there are two types of exceptions: Checked and Unchecked Exceptions.
Java Exception Class Heirarcy
Exception Class Heirarchy
Checked Exceptions: These are the type of exceptions for which the compiler checks to ensure that your code is prepared for handling such exceptions. These are the exceptions that you can expect to occur frequently and you must handle them in your code. The conditions that generate such exceptions are generally outside the control of your program and they can occur in a correct program. But you can anticipate them and thus you must write code to deal with them. Programmatically, checked exceptions are the instances of the Exception class or one of its subclasses, excluding RuntimeException subtree.

Unchecked Exceptions: The compiler does not check for such type of exceptions. Unchecked Exceptions comprise of  run time exceptions (of type RuntimeException or its subclasses) and errors (of type Error or its subclasses). Runtime Exceptions occur due to program bugs and include exceptions such as division by zero and invalid array indexing. You can not recover from an unchecked exception and you are not required to handle such type of exceptions either, but still you can do so if you want. ArithmeticException class is an example of unchecked exception. Errors are the exceptions that are not expected to be caught under normal circumstances by your program. They are used by the Java run time environment to indicate errors related to run time environment itself. Stack Overflow is an example of error.

Exception Handling in Java

We will come across five keywords while learning Exception Handling in java: try, catch, finally, throw and throws. To handle the java exceptions, try and catch are the two major keywords that you will be using. Simply enclose the code that is expected to produce some kind of exception by try block and catch that exception in the catch block immediately following the try block. Whenever an exception occurs, an object is created and thrown containing the information about that exception. To catch this thrown block, you must specify the catch block(s). The catch block receives this thrown object as its parameter and then you can specify the code to handle this exception.
Java Program Example to illustrate the Exception Handling in java.
  class DemoExceptionHandling{
 public static void main(String args[]){
  int a=5;
  int b=0;
  System.out.println("We are about to enter in a try block!...");
  try {
   System.out.println("a/b="+a/b);
   System.out.println("This will not be printed.");
   } catch (ArithmeticException ae){
    System.out.println("Exception Caught: "+ae.getMessage());
    }
  System.out.println("Statement after catch block.");
 }
}

In the above example ArithmeticException thrown by the try block is caught by the catch block which is coded to receive ArithmeticException object. Now what if, if the catch block would contain some other parameter type than the thrown exception? In that case, the exception thrown will not be caught due to the absence of appropriate catch block and the program will terminate without executing any other line from the method. You may create as many catch blocks as you want, each for receiving the particular types of exception. Alternatively, you can create a catch block to receive all types of exceptions by configuring it to receive the object of class Exception itself, which is the super class of all the exceptions.
One major benefit of having an error signalled by an exception is that it separates the code that deals with errors from the code that is executed when things are moving along smoothly. Another positive aspect of exceptions is that they provide a way of enforcing a response to particular errors.

Use of finally Block in Java Exception Handling

In case the exception could not be caught, the program will terminate and no further lines of code will be executed after the line where the exception occurred. But in some situation you may desire to execute some lines of code irrespective of the fact whether or not the catch block corresponding to the try block has been caught. In that you should use finally block. The finally block is executed almost always even if the exception is not caught.
Example Java Program to illustrate the use of finally block
class DemoExceptionHandling{
 public static void main(String args[]){
  int a=5;
  int b=0;
  System.out.println("We are about to enter in a try block!...");
  try {
   System.out.println("a/b="+a/b);
   System.out.println("This will not be printed.");
   } catch (ArrayIndexOutOfBoundException oe){
    System.out.println("Exception Caught: "+oe.getMessage());
    }
    finally{
     System.out.println("Finally block will execute always!");
    }
  System.out.println("Statement after catch and finally block.");
 }
}

In the above example, the finally block will be executed always, whether the exception is caught or not. If the exception is caught by the appropriate catch block, then the execution of the program will continue after the finally block also. But if the exception in try block has not been caught by the appropriate catch block, then the control will be transferred to the finally block and after that the program will terminate.

What happens when exception handler is not provided?

You must be thinking what would happen, if exception handling is avoided in a java program.  When you do not provide provisions of exception handling, java does it for you by default. Whenever an exception occurs, the java run-time detects it and creates an exception object and throws it. Now since there are no exception handlers created, the thrown exception object will be caught by the default handler provided by the java run time. The default handler displays a string describing the exception, prints a stack trace from the point at which the exception occurred, and terminates the program. So, in order to avoid this immature termination of program, exception handling is used.
Exceptions should not be overused at all. The reason for this is that dealing with exceptions involves quite a lot of processing overhead, so if your program is handling exceptions a lot of the time it will be a lot slower than it needs to be. For Example, a user entering incorrect input to your program for instance is a normal event and should be handled without recourse to exceptions.
This post is just for the basic introduction of the Exceptions in Java and Handling Exceptions in Java. To know little more about Exception Handling in Java such as nested try blocks, difference between throw and throws and creating your own exception classes, Read Java Exception Handling Tutorial-2.

11 comments:

  1. Java is very technical language, thanks for share tutorial.

    ReplyDelete
  2. good tutorial. looking forward for more java titles.

    Rob.

    ReplyDelete
  3. Your blog is very informative and gracefully
    your guideline is very good.Thank you
    Regional pharmacy college
    deepshikha group of colleges

    ReplyDelete
  4. Those who wish to learn ANDROID

    VISIT ANDROIDITUTS

    http://www.androidituts.com

    ReplyDelete
  5. Best Java/J2EE Training Institute In Chennai ???


    Hi Friends ,

    I have experience of java/j2ee training from virtuous technology located @ adyar (week end batches) , one of the best java/j2ee training institute fulfulling the students requirements.All the trainers are well experienced and well equiped. Make it useful..,

    ReplyDelete
  6. Thanks for sharing this information Java language is very important to make a secure web application.

    Java development Company India

    ReplyDelete
  7. Your technical information related with java programming is very useful and interesting. Also share updated details about java in your website. Thanks for sharing this article.

    ReplyDelete
  8. Very nice post , thanks for sharing this post with us and gave us a good information regarding java exception handling tutorial .

    ReplyDelete
  9. A great post without doubt. The information shared is of top quality which has to get appreciated at all levels. Well done keep up the good work.

    ReplyDelete

Please leave your valuable comments here...