Pages

Exception Handling in JAVA


What is Exception ?


Exception handling is a mechanism of converting system error messages into user friendly messages. The exception handling is one of the powerful mechanisms provided in java. It provides the mechanism to handle the runtime errors so that normal flow of the application can be maintained.

Errors are of two types. They are compile time errorsand run time errors. Compile time errors are those which are occuring because of poor understanding of the language. Run time errors are those which are occuring in a program when the user inputs invalid data. The Run time errors must be always converted by the JAVA programmer into user friendly messages by using the concept of exception handling.


  • Dictionary Meaning: Exception is an abnormal condition.
  • In java, exception is an event that disrupts the normal flow of the program. It is an object which is thrown ar runtime.

Exception hierachy



There are mainly two types of exceptions: checked and unchecked where error is considered as unchecked exception. The sun micro system says there are three types of exceptions:
  1. Checked Exception
  2. Unchecked Exception
  3. Error
Unchecked Exception

The classes that extend RuntimeException are known as unchecked exceptions.
e.g:-
         ArithmeticException, NullPointerException. ArrayIndexOutOfBoundsException etc. Unchecked exceptions are not checked at compile-time rather they are checked at runtime.

Checked Exception

The classes that extends Throwable class except RuntimeException and Error are known as checked exceptions.
e.g:-
       IOException, SQLException etc. Checked exceptions are checked at compile-time.

Error

Error is irrecoverable.
e.g:- OutOfMemoryError, VirtualMachineError, AssertionError etc. Common scenarios of Exception Handling where exceptions may occur.

There are given some scenarios where unchecked exceptions can occur. They are as follows
  • If we divide any number by zero, there occurs an ArithmeticException.
  • If we have null value in any variable, performing any operation by the variable occurs an NullPointerException.
  • The wrong formatting of any value, may occur NumberFormatException. Suppose I have a string variable that have characters, converting this variable into digit will occur NumberFormatException.
  • If you are inserting any value in the wrong index, it would result ArrayIndexOutOfBoundsException

Five keywords in Exception Handling
  1. try
  2. catch
  3. finally
  4. throw
  5. throws
class ClassName
{
  public static void main(String args[])
  {
     Block of statements which are to be monitored by JVM ar runtime.
     throw Throwable_object;
  }
  catch(Type_of_exception1 object1)
{
  Exception handle statement
}
.
.
.
.
catck(Type_of_exception objectn)
{
  Exception handle statement
}
finally
{
  Statement must execute
}

}
}
}

try block

  • This is the block in which we write the block of statements which are to be monitored by JVM at runtime i.e, try block must contain those statements which causes problems at runtime.
  • If any exception is taking place the control will be jumped automaticallu to appropriate catch block.
  • If any exception is taking place in try block will be terminated and the rest of the statements in try block will not be executed.
  • for every try block we must have at least one catchblock. It is highly recommended to write 'n' number of catch's for 'n' number of problematic statements.

catch block
  • This is used for providing user friendly message by catching system messages.
  • In the catch we must declare an object of the appropriate execution class and it will be internally referenced JVM whenever the appropriate situation taking place.
  • If we write 'n' number of catch's as a part of JAVA program then only one catch will be exceuting at any point.
  • After executing appropriate catch block even if we use return statement in the catch block the control never goes to try block.

Example without handling Exception


class Demo
{
public static void main(String[] args) 
{
System.out.println("Hello World!");
int data = 50/0;
System.out.println("rest of the code");
}
}



As displayed in the above example, rest of the code is not executed . The JVM firstly checks whether the exception is handled or not. If exception is not handled, JVM provides a default exception handler that performs the following tasks:
  • Print out exception description.
  • Prints the stack trace (Hierarchy of methods where the exception occured).
  • Causes the program to terminate.
But if exception is handled by the application programmer, normal flow of the application is maintained i.e. rest of the code is executed.

Example of handling the Exception


class Simple
{
public static void main(String [] args)
{
try
{
int data = 50/0;
}
catch (ArithmeticException e)
{
System.out.println(e);
}
System.out.println("rest of the code...");
}
}


Example of using multiple catch block

class Excep1
{
public static void main(String [] args)
{
try
{
int a[] = new int[5];
a[5] = 30/0;
}
catch (ArithmeticException e)
{
System.out.println("task1 is completed");
}
catch (ArrayIndexOutOfBoundsException e)
{
System.out.println("task2 completed");
}
catch (Exception e) 
{
System.out.println("common task completed");
}
System.out.println("rest of the code...");
}
}


Rules:
  • At a time only one exception is occured and at a time only one catch block is executed.
  • All catch blocks must be ordered from most specific to most general i.e. catch for ArithmeticException must come before catch of Exception.

EXAMPLE TO HANDLE EXCEPTION IN A PROPER SEQUENCE

class Excep2
{
public static void main(String [] args)
{
try
{
int a[] = new int[5];
a[5] = 30/0;
}
catch (Exception e)
{
System.out.println("Common task completed");
}
catch (ArithmeticException e)
{
System.out.println("task1 is completed");
}
catch (ArrayIndexOutOfBoundsException e)
{
System.out.println("task2 is completed");
}
System.out.println("rest of the code...");
}
}



Nested try block

try block within a try block is known as nested try block. Sometimes a situation may arise where a part of a block may cause one error and the entire block itself may cause another error. In such cases, exception handlers have to be nested.

EXAMPLE OF NESTED try BLOCK

class Excep3
{
public static void main(String [] args)
{
try
{
try
{
System.out.println("going to divide");
int b = 49/0;
}
catch (ArithmeticException e)
{
System.out.println(e);
}
try
{
int a[] = new int[5];
a[5] = 4;
}
catch (ArrayIndexOutOfBoundsException e)
{
System.out.println(e);
}
System.out.println("other statement");
}
catch (Exception e)
{
System.out.println("handled");
}
System.out.println("normal flow..");
}
}




throw keyword

The throw keyword is used to explicitly  throw an exception. We can throw either checked or unchecked exception. The throw keyword is mainly used to throw custom exception. In this example, we have created the validate method that takes integer value as a parameter. If the age is less than 18, we are throwing the ArithmeticException otherwise print a message "Congratulation, You are valid to Vote."

EXAMPLE OF throw

class Excep4
{
static void validate(int age)
{
if(age<18)
throw new ArithmeticException("not valid to Vote");
else
System.out.println("Congratulation, You are valid to Vote");
}
public static void main(String [] args)
{
validate(15);
System.out.println("rest of the code");
}
}


throws keyword

This is the keyword which gives an indication to the calling function to keep the called function under try block and catch block. The throw keyword is used to declare an exception. It gives information to the programmer that there may occur an exception so it is better for the programmer to provide the exception handling code so that normal flow can be maintained.

Exception handling is mainly used to handle the checked exceptions. If there occurs any unchecked  exception such as NullPointerException, it is programmers fault that he is not performing check up before the code being used.

void method_Name() throws exception_class_name
{
       ....................
       .....................
}

EXAMPLE OF throws

import java.io.IOException;
class Excep5
{
void checkexcep() throws IOException
{
throw new IOException("device error"); //Checked exception
}
void check1() throws IOException
{
checkexcep();
}
void another() 
{
try
{
check1();
}
catch (Exception e)
{
System.out.println("Exception handled");
}
}
public static void main(String [] args)
{
Excep5 obj = new Excep5();
obj.another();
System.out.println("normal flow..");
}
}



Difference between throw and throws
Throw Throws
throw is used to explicitly throw an exception. throws is used to declare an exception.
checked exception can not be propagated without throws. checked exception can be propagated with throws.
throw is followed by an instance. throws is followed by class.
throw is used within the method. throws is used with the method signature.
You can't throw multiple exception. You can declare multiple exception
e.g.
public void method() throws IOException, SQLException.



finally block

  • The finally block is a block that is always executed. It is mainly used to perform some important tasks such as closing connection, stream etc.
  • finally block can be used to put "cleanup" code such as closing a file, closing connection etc.
  • This is the block which is executing compulsory whether the exception is taking place or not.
  • Writing the finally block is optional.
try
{
   ...................
   ...................
}
finally
{
}

EXAMPLE OF finally WHEN NO EXCEPTION

class Excep6
{
public static void main(String [] args)
{
try
{
int a = 45/5;
System.out.println(a);
}
catch (NullPointerException e)
{
System.out.println(e);
}
finally
{
System.out.println("finally is always executed");
}
System.out.println("rest of the code..");
}
}


EXAMPLE OF finally IN CASE OF EXCEPTION OCCUR

class Excep6
{
public static void main(String [] args)
{
try
{
int a = 45/0;
System.out.println(a);
}
catch (NullPointerException e)
{
System.out.println(e);
}
finally
{
System.out.println("finally is always executed");
}
System.out.println("rest of the code..");
}
}


Rules:

  • For each try block there can be zero or more blocks, but only one finally block.
  • The finally block will not be executed if program exits (either by calling System.exit() or by causing a fatal error that causes the process to abort).

Exception Propagation

An exception is first thrown from the top to the stack and if it is not caught, it drops down the call stack to the previous method, If not caught there, the exception again drops  down to the previous nethod, and so on until they are caught or until they reach the very bottom of the call stack. This is called exception propagation

By default Unchecked Exceptions are forwarded in calling chain propagated.

EXAMPLE OF EXCEPTION PROPAGATION WITH UNCHECKED EXCEPTION

class Demo
{
void fun1()
{
int a = 50/0;
}
void fun2()
{
fun1();
}
void fun3()
{
try
{
fun2();
}
catch (Exception e)
{
System.out.println("Here Exception is handled");
}
}
public static void main(String [] args)
{
Demo obj = new Demo();
obj.fun3();
System.out.println("normal flow");
}
}


In the above example exception occurs in fun1() method where it is not handled, so it is propagated to previous fun2() method where it is not handled, again it is propagated to fun3() method where exception is handled. Exception can be handled in any method is call stack either in main()  method, fun3() method, fun2() method or fun1() method.

By default, Checked Exceptions are not forwarded in calling chain (propagated).

EXAMPLE OF EXCEPTION PROPAGATION WITH CHECKED EXCEPTION

class Excep8
{
void fun1() throws java.io.IOException
{
throw new java.io.IOException(); //generate checked exception
}
void fun2() throws java.io.IOException
{
fun1();
}
void fun3()
{
try
{
fun2();
}
catch (Exception e)
{
System.out.println("Here Exception is handled");
}
}
public static void main(String [] args)
{
Excep8 obj = new Excep8();
obj.fun3();
System.out.println("normal flow");
}
}


Rules for Exception handling with method overriding.
  • If the super class method does not declare an exception, subclass overridden method can't declare the checked exception but it can declare unchecked exception.
  • If the super class method declares an exception, subclass overridden method can declare same, subclass exception or no exception but can't declare parent exception.

If the super class method doesn't throw an exception
If the super class method doesn't declare an exception, subclass overridden method can't declare the checked exception. If the super class method does not declare an exception, subclass overridden method can't declare the checked exception but can declare unchecked exception.

EXAMPLE OF EXCEPTION HANDLING WITH METHOD OVERRIDING IN CASE OF CHECKED EXCEPTION

import java.io.*;
class Parent
{
void msg()
{
System.out.println("Parent class");
}
}
class Child extends Parent
{
void msg() throws IOException
{
System.out.println("Child class");
}
public static void main(String args[])
{
Parent p = new Child();
p.msg();
}
}


EXAMPLE OF EXCEPTION HANDLING WITH METHOD OVERRIDING IN CASE OF UNCHECKED EXCEPTION

import java.io.*;
class Parent1
{
void msg()
{
System.out.println("Parent class");
}
}
class Child1 extends Parent1
{
void msg() throws ArithmeticException
{
System.out.println("Child class");
}
public static void main(String [] args)
{
Parent1 p = new Child1();
p.msg();
}
}


If the super class Method throw an Exception
If the super class method declares an exception, subclass overridden method can declare same, subclass exception or no exception but can't declare parent exception.

EXAMPLE OF OVERRIDDEN METHOD DECLARES PARENT EXCEPTION

import java.io.*;
class Parent2
{
void msg() throws ArithmeticException
{
System.out.println("Parent class");
}
}
class Child2 extends Parent2
{
void msg() throws Exception
{
System.out.println("Child class");
}
public static void main(String args[])
{
Parent2 p = new Child2();
try
{
p.msg();
}
catch (Exception e)
{
}
}
}


Number of ways to find details of the Exception
In JAVA  there are three ways to find the details of the exception. They are:
  • Using an object of  java.lang.Exception class.
  • Using public void printStackTrace method and 
  • Using public string getMessage method.

Using on object of java.lang.Exception:

An object of Exception class prints the name of the exception and nature of the message.
For example:
 try
{
int x = Integer.parseInt("10x");
}
catch (Exception e)
{
System.out.println(e);
//java.lang.NumberFormatException : for input string 10x
//     name of the exception       nature of the message
}


Using printStackTrace method

This is the method which is defined in java.lang.Throwable class and it  is inherit into java.lang.Error class and java.lang.Exception class. This method will display name of the exception, nature of the message and the line number where the exception has taken place.
For example:
try
{
int x = 10/0;
}
catch (Exception e)
{
e.printStackTrace();
//java.lang.ArithmeticException : /by zero : at line no: 4
// name of the exception      nature of the message line number
}


Using getMessage method

This is also a method which is defined in java.lang.Throwable class and it is inherited into both Error and Exception classes. This method will display only nature of the message.
For example:
try
{
int x = 10/0;
}
catch (Exception e)
{
System.out.println(e.getMessage());// /by zero
}


Custom Exception

User defined  exceptions are those which are developed by JAVA programmer as a part of application development for dealing with specific problems such as negative salaries, negative ages, etc. If you are creating your own Exception that is known as custom exception or user-defined exception.

Guide lines for developing user defined exceptions
  1. Choose the appropriate package name.
  2. Choose the appropriate user defined class.
  3. Every user defined class which we have choose in step 2 must extends either java.lang.Exception or java.lang.RunTimeException class.
  4. Every user defined sub-class Exception must contain a parameterized constructor by taking string as a parameter.
  5. Every user defined sub-class exception parameterized constructor must called parameterized constructor of either java.lang.Exception or java.lang.RuntimeExcption class by using super(String parameter always).

EXAMPLE OF CUSTOM EXCEPTION

class InvalidAgeException extends Exception
{
InvalidAgeException(String s)
{
super(s);
}
}
class Excep9
{
static void validate(int age) throws InvalidAgeException
{
if(age<18)
throw new InvalidAgeException("not valid");
else
System.out.println("Welcome to vote");
}
public static void main(String args[])
{
try
{
validate(13);
}
catch (Exception m)
{
System.out.println("Exception occured: "+m);
}
System.out.println("rest of the code.....");
}
}

No comments:

Post a Comment