Monday, 18 September 2017

Exception Handling In Java

EXCEPTION

An exception is a condition that is caused by a run-time error in a program. When the java interpreter encounters an error such as dividing y zero, it creates an exception object and throws it (i.e., informs us that an error has occurred).

EXCEPTION HANDLING


If the exception object is not caught and handled properly, the interior will display an error message and will terminate the program. If we want the program to continue with the exception of the remaining coffee, then we should try to carry the exception object thrown by the error condition and then display an appropriate message for taking corrective actions. This task is known as exception handling.
The purpose of exception handling mechanism is to provide a means to detect and report an “exceptional circumstances” so that appropriate action can be taken.
The error handling code by consists of two segments, one to detect an error and to their exceptions and the other to catch exceptions and to take appropriate actions.

COMMON JAVA EXCEPTIONS

EXCEPTION TYPE
CAUSE OF EXCEPTION
ArithmeticException
Caused by math errors such as division by zero
ArrayIndexOutOfBoundsException
Caused by bad array indexes
ArrayStoreException
Caused when a program tries to store the wrong type of data in an array
FileNotFoundException
Caused by an attempt to access a nonexistent file
IOException
Caused by general I/O failures, such as inability to read from a file
NullPointerException
Caused by referencing a null object
NumberFormatException
Caused when a conversion between strings and number fails
OutOfMemoryException
Caused when there's not enough memory to allocate a new object
SecurityException
Caused when an applet tries to perform an action not followed by the browser's security setting
StackOverflowException
Caused when the system runs out of stack space
StringIndexOutOfBoundsException
Caused when a program attempts to access a nonexistent character position in a string

SYNTAX OF EXCEPTION HANDLING CODE


The basic concepts of exception handling are throwing an exception and catching it.
Java used a keyword try to preface a block of coffee that it's likely to cause an error condition and”throw” an exception. A catch block defined by the keyword catch “catches” the exception “thrown” by the try block and handles it appropriately. The catch block is added immediately after the try block. The following example illustrates the use of simple try and catch statements.

………
try
{

// statements
// to generate an exception

}
catch (Exception-type e)
{

// statement
// to process the exception

}


MULTIPLE CATCH STATEMENTS


It is possible to have more than one catch statement in the catch block as shown below

……
……
try
{
// statement
// generates an exception
}
catch(Exception-Your-1 e)
{
// statement
}
catch(Exception-Your-2 e)
{
//statement
}
.
.
.
catch(Exception-Your-N e)
{
//statement
}
…..
…..


When an exception in a try block is generated, the Java treats the multiple catch statements like cases in a switch statement. The first statement whose parameters matches with the exception object will be executed, and the remaining states will be skipped.
Note that Java does not require any processing of the exception at all. We can simply have a catch statement with an Empty block to avoid program abortion.

Example:-
catch(Exception e) :
The catch statement simply ends with a semicolon, which does nothing. This statement will catch an exception and then ignore it.


Example of try and catch for exception handling:--


Note that the program gets not stop at the point of exceptional condition. It catches the error condition, prints the error message, and then continue the execution as if nothing has happened.

public class Demo{ 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 multiple catch blocks:--

public class MultipleCatchBlock{  
  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("task 2 completed");}   catch(Exception e){System.out.println("common task completed");}  
  System.out.println("rest of the code...");  
 }  





Use of finally statement:--
Java supports another statement known as finally statement that can be used to handle an exception that is not caused by any of the previous catch statements. Finally block can be used to handle in exception generated within a try block. It may be added immediately after the try block or after the last catch block soon as follows.

Eg:1
try
{
 …...
 ……
}
finally
{
 ……
 ……
}


Eg:2
try
{
 ……
 ……
}
catch(.....)
{
 ……
 ……
}
catch(.....)
{
 …..
 …..
}
.
.
.
finally
{
 …..
 …..
}

Note:- when you finally block is, this is guaranteed to execute, regardless of whether or not an exception is thrown. As a result we can used to perform certain housekeeping operations such as closing files and releasing system resources.


THROWING OUR OWN EXCEPTIONS

There may be times when we would like to through our own exceptions. We can do this by using the keyboard throw as follows:

throw new Throwable_subclass

Examples:

throw new ArithmeticException ();
throw new NumberFormatException ();

EXAMPLE FOR THROWING OUR OWN EXCEPTION:--

import java.lang.Exception;

class MyException extends Exception
{
  MyException (String message)
  {
   super (message);
  }
}

class TestMyException
{
 public static void main (String args[])
 {
  int x=5, y=1000;
  try
  {
    float z = (float) x / (float) y;
    if(z < 0.01)
     {
      throw new MyException (“Number is too small”);
      }
  }
  catch (MyException e)
   {
      System.Out.println(“Caught my Exception”);
      System.Out.println(e.getMessage() );
   }
  finally
   {
    System.Out.println(“I am always here”);
   }
 }
}


Output:--

Caught my Exception
Number is too small
I am always here

The object in which contains the error message “Number is too small” is God by the catch block which then displays the message using the getMessage() method.

Note that this program shows the use of finally block. The last line of output is produced by the final block.

No comments:

Post a Comment