Thursday, May 30, 2013

Exception Handling In Java(try,catch,throw and throws)



Exception:
1)      Errors at runtime are called exceptions.
2)      Whenever user enters wrong input or performs illegal operation then we will get system error message or exception.
3)      Every java programmer must develop their application with the concept of Exception handling to make the application as robusted.
4)      It is strongly recommended for java programmer to have forecasting (future) knowledge regarding what type of data is going to be entered by the ordinary users.

Types of exception:
In java we have two types of exception: -
1)      Predefined or built-in exception
2)      User-defined or custom-defined or secondary defined exception

Predefined exception:

Predefined exceptions are those which are developed by Sun Micro Systems and supplied as a part of JDK to deal with universal problems such as division by zero, invalid number format problem etc.

Pre-defined exceptions are of two types. They are:
1)      Asynchronous Exception:  
·         Asynchronous Exception are those exceptions which always deal with the hardware problems such as mouse failure, keyboard failure, power failure etc.
·         In order to deal with Asynchronous Exception, we have a predefined class called “java.lang.Error”. Here Error class is super class for all Asynchronous Exceptions.
·         Example of Asynchronous Exception is StackOverflowError.

2)      Synchronous exception:
·         Synchronous exceptions are those which always deal with programmatic errors. Synchronous exceptions are divided into two types. They are:
(a)    Checked Exception
(b)   Unchecked Exception

Checked Exceptions are those which deal with the programmatic compile-time errors (PCE).
Regarding this we have only two errors: -
a)      ClassNotFoundExceptrion.
b)      InterfaceNotFoundException.

Unchecked Exceptions are those which deal with programmatic runtime errors (PRE). The following exceptions are the example of unchecked exceptions:
a)      ArithmeticException
b)      NumberFormateException.
c)      ArrayIndexOutOfBoundException.

·         We have java.lang.Exception to deal with all synchronous exception to deal with Synchronous Exception i.e. java.lang.Exception class is a super class for all synchronous Exception.








 Hierarchy chart of Exceptions:


 




















How Exceptions happens internally:




SEM-   System Error Messages
UFM-   User Friendly Messages
EH-      Exception Handling
Steps:
  1. Passing Relevant Input to java program.
  2. Java program gives Relevant results.

1)      User input irrelevant data to the java program.
2)      JVM can’t process or unable to process that irrelevant data & contacts to Java Runtime Environment (JRE).
3)      JRE in turns contacts to java.lang.Throwable class. It is a pre-defined class which is used to determine the type of Exception.
4)      java.lang.Throwable class gives the type of Exception to JRE i.e. either Synchronous or Asynchronous. java.lang.Throwable is the super class for java.lang.Error(Synchronous) & java.lang.Exception(Asynchronous).
5)      JRE hands over the type of Exception to java API.
6)      6.1- 6.2 Java Exception API checks the types of exception and hands over the type of Exception to either java.lang.Error(6.1) or java.lang.Exception(6.2).
7)      It is the responsibility of the 6th step to give the appropriate subclass of either java.lang.Error or java.lang.Exception to JRE.
8)      Finally, the JRE gives an appropriate exception class or Error class to JVM.
9)      After receiving an appropriate class from JRE its object will be created by the JVM.
10)  After creating the appropriate object of Exception or Error class, JVM generates the System Error Message (SEM) which is not understandable for ordinary users.
11)   & 12) System Error Messages are caught by the java programmers as they convert it in to user-friendly messages (UFM) by using the concept of Exception handling to make their program robusted.  

Alternate Definition for Exception:
An Exception is an object occurs at Runtime and it describes the nature of the message, such that either System Error Messages or User Friendly Messages

User defined / Custom defined Exception:
User defined / custom defined exceptions are those exceptions which are developed by java programmers to deal with specific problems such as negative salary or negative age etc.

Steps/ guidelines to develop User-defined Exceptions:
1)      Choose the appropriate package name and ensure that the package statement must be the first statement of the java program.
2)      Choose the appropriate user defined exception class.
3)      The class which we have chosen must be extending to either java.lang.Exception or java.lang.RuntimeException. (RuntimeException is the subclass of the Exception class) 
4)      Every user defined Exception class must contain a parameterized constructor by taking String as a parameter.
5)      Parameterized constructor of every user defined exception subclass must call a parameterized constructor of java.lang.Exception class by using “super (String)”.

Exception Handling:
·         It is a process of converting System Error Message (SEM) into User Friendly Message (UFM).
·         System Error Messages are those which are occurring at runtime and those messages are not understood by ordinary users.
·         User friendly messages are those which are easily understood by ordinary users of the technology or project.
·         It is strongly recommended to convert the system error messages into user friendly.

Class Demo
{
public static void main(String args[])
{
String s1=args[0];
String s2=args[1];
int n1=Integer.ParseInt(s1);
int n2=Integer.ParseInt(s2);
float n3= n1/n2;
System.out.println (“division :” +n3);
}
}
Possible executions:
Compilation:
C:\>javac Demo.java
Execution:
C:\>java Demo// No Input
Exception in 1st Line: ArrayIndexOutOfBoundException.

C:\>java Demo 20 //2nd input not given
Exception in 2nd Line: ArrayIndexOutOfBoundException.

C:\>java Demo 10x 20
Exception in 3rd Line: NumberFormatException.

C:\>java Demo 10 20y
Exception in 4th Line: NumberFormatException.

C:\>java Demo 10 0
Exception in 6th Line: ArithmeticException.

So, we create catch block to supply user friendly messages as under:

How to handle exception:
 In order to handle runtime error in java, as a part of Exceptional Handling, we have 5 keywords. They are:
1)      try
2)      catch
3)      finally
4)      throws
5)      throw

Syntax for handling exception:
try
{
            // Block of statements which are to be monitored by the JVM at run time.
}
catch(TypeOfException-1 obj1)
{
            // Block of statements which prove user friendly messages.
}
catch(TypeOfException-2 obj2)
{
            // Block of statements which prove user friendly messages.
}
catch(TypeOfException-3 obj3)
{
            // Block of statements which prove user friendly messages.
}
.
.
catch(TypeOfException-N objN)
{
            // Block of statements which prove user friendly messages.
}
finally
{
            Block of statements which will execute compulsorily and will release the resources allocated in try block.
}

try block:

(i)     This is the block of which we write the set of statements which are to be monitored by JVM at runtime. In other words, if there are any problematic statements available in our java program then that must be written under try block.
(ii)   Whenever any runtime error takes place in the try block, program execution will be terminated then and there (immediately) and control jumps to the appropriate catch block.
(iii) When the control goes to catch block the set of statements will be executed which are available in catch block and control never returns to try block even though we use the return statement.
(iv) For each and every try block we must write at least one catch block. But it is recommended for java program to write n# of catch blocks for n# of problematic statements to make the program as robusted.
(v)   After completion of try block, we must write catch block i.e. No intermediate statements are allowed between try and catch blocks.

catch block:

(i)     Catch block will be executing when runtime problem is taking place in try block.
(ii)   At any point of time, only one catch block is executing among n# of catch blocks.
(iii) In this, we declare an object of specific exception and it will be referenced by the JVM internally whenever the particular exception takes place.

finally block:

(i)     This is the block in which we write the set of statements which will execute compulsorily.
(ii)   Finally block is basically used to release the resource (files, database connection, etc.) which are obtained in try block.
(iii) Writing finally block is optional.

throws:
(i)     “throws” is a keyword which is used to throw either predefined or user defined or both exceptions which are occurring as a part of method body.
(ii)   “throws” keyword gives an indication to the calling method to keep the called method under try and catch blocks.
(iii) Syntax for throws keyword:
returnType methodName(param) throws TypeOfException-1, TypeOfException-2,.,TypeOfException-N
{
      Block of statements
}
(iv) “throws” keyword must be used as a part of method heading only.

            throw:
(i)     “throw” is a keyword which is used to throw user defined exception as a part of methods body.



Example



Class Demo
{
public static void main(String args[])
{
try
{
String s1 =args[0];
String s2=args[1];

int n1=Integer.ParseInt(s1);
int n2=Integer.ParseInt(s2);

float n3= n1/n2;
System.out.println (“division :” +n3);
}
catch(ArithmeticException ae)
{
System.out.println(“Please do not pass zero as denominator.”);
}
catch(NumberFormatException nfe)
{         
System.out.println(“Please pass Integer values only.”);
}
catch(ArrayIndexOutOfBoundsException ae)
{
System.out.println(“Please pass two values.”);
}
catch(Exception e)
{
System.out.println(e);
}
}// psvm
} //class

NOTE: Exception is a super class of all the Synchronous Exceptions. So, if there is unknown exception then we can call super class object


No comments:

Post a Comment