Thursday, March 28, 2013

  •                                                      EXCEPTION IN JAVA

EXCEPTION:(exception is an abnormal case)
                 
                       An exception is an event, which occurs during the execution of a program, that disrupts the normal flow of the program's instructions. In other words exception is a run time error.

                       Exception handling is a mechanism to handle run time errors.




 Common situations where Exception Arises.

1)If we divide a number by zero there occurs Arithmetic exception.

       int a=19/0;//Arithmetic Exception
2)Performing an operation to a variable which is assigned to null.

       String s=null;
System.out.println(s.length());

3)Inserting value in wrong index results ArrayIndexOutOfBoundException.
int a[]=new int[4];
a[55]=100;//ArrayIndexOutOfBoundException

TYPES OF EXCEPTIONS:
                                         
 In java there are two types of Exceptions
1)Checked Exception.
2)Unchecked Exception.

But SUN MICROSYSTEM says  there exists 3 types of Exceptions they are as follows.
1)Checked Exception.
2)Unchecked Exception.
3)Error.





1)Checked Exception:
  • Checked exceptions in Java extend the java.lang.Exception class.
  • Checked Exception.are sub_classes of Exception.
  • You should compulsorily handle the checked exceptions in your code, otherwise your code will not be compiled. i.e you should put the code which may cause checked exception in try block. "checked" means they will be checked at compile time itself.
  • There are two ways to handle checked exceptions. You may declare the exception using a throws clause or you may use the try..catch block..
  • The most perfect example of Checked Exceptions is IOException which should be handled in your code Compulsorily or else your Code will throw a Compilation Error.
2)Unchecked Exception:

  •  Unchecked exceptions extend the java.lang.RuntimeException.
  •  Unchecked Exception are subclasses of RuntimeException, and are usually implemented using IllegalArgumentException, NullPointerException, or IllegalStateException.
  • The most Common examples are ArrayIndexOutOfBoundException, NUllPointerException ,ClassCastException.
  • Unchecked exceptions can occur anywhere in a program and in a typical program can be very numerous. Therefore, the cost of checking these exceptions can be greater than the benefit of handling them. Thus, Java compilers do not require that you declare or catch unchecked exceptions in your program code. Unchecked exceptions may be handled as explained for checked exceptions in the following section.
3)ERROR:
                 When a dynamic linking failure or other hard failure in the Java virtual machine occurs, the virtual machine throws an Error. Simple programs typically do not catch or throw Errors.
Java exception is handled using 5 key words.
1)try.
2)catch
3)throw
4)throws
5)finally

//Sample Exception program.

public class ExceptionDemo {
public static void main(String[] args) {
int i = 1 / 0;
System.out.println("After division by 0");

}
}

 Here, by doing 1/0, the program will stop abruptly. And it will give a weird error message. Like,
Exception in thread "main" java.lang.ArithmeticException: / by zero 
          at Exception_Demo.main(Exception_Demo.java:6)

1)TRY BLOCK:

                              The first step in constructing an exception handler is to enclose the code that might throw an exception within a try block. In general, a try block looks like the following:

try {
    code
}

2)CATCH BLOCK:

You associate exception handlers with a try block by providing one or more catch blocks directly after the try block. No code can be between the end of the try block and the beginning of the first catch block.

try {

} catch (ExceptionType name) {

} catch (ExceptionType name) {

}

Each catch block is an exception handler and handles the type of exception indicated by its argument. The argument type, ExceptionType, declares the type of exception that the handler can handle and must be the name of a class that inherits from the Throwable class. The handler can refer to the exception with name.

The catch block contains code that is executed if and when the exception handler is invoked. The runtime system invokes the exception handler when the handler is the first one in the call stack whose ExceptionType matches the type of the exception thrown. The system considers it a match if the thrown object can legally be assigned to the exception handler's argument.


//Example program using TRY,CATCH.

class Try_Catch
{
public static void main(String args[])
{
try
{
int a=0;
int b=10/a;
System.out.println("This will not be printed");
}
catch(ArithmeticException e)
{
System.out.println("division by 0");
}
System.out.println("After Try_Catch block");
}
}

OUTPUT:
                  division by 0
                 After Try_Catch block   
          
3)FINALLY:
                     The finally block always executes when the try block exits. This ensures that the finally block is executed even if an unexpected exception occurs. But finally is useful for more than just exception handling — it allows the programmer to avoid having cleanup code accidentally bypassed by a return, continue, or break. Putting cleanup code in a finally block is always a good practice, even when no exceptions are anticipated.

  public class FinallyDemo{
public static void main(String args[]){
try{
System.out.println(“\n\tInside main method…”);
throw new ArithmeticException();
}catch(ArithmeticException e){}
finally{
System.out.println(“\nInside finally block…”);
}
System.out.println(“\nLast statement in main…”);
}
}
OUTPUT:

               Inside main method…
               Inside finally block…
               Last statement in main…


MULTIPLE CATCH CLAUSES.

class Multi_Catch
{
public static void main(String args[])
{
try
{
int arr[]=new int[4];
arr[5]=19/0;
}
catch(ArithmeticException e1)
{
System.out.println(“first CATCH block Executed”);
}
catch( ArrayIndexOutOfBoundsException e2)
{
System.out.println(“second CATCH block Executed”);
}
catch( Exception e3)
{
System.out.println(“third  CATCH block Executed”);
}
finally
{
System.out.println("finally block");
}
}
}

OUTPUT:
                 first CATCH block Executed
                 finally block


NOTE:
             1)At a time only one Exception occurs.
              2)At a time only one CATCH BLOCK will be executed. 


class Nested_Try{
public static void main(String args[]){
try{


try
{
System.out.println("welcome to Nested_Try block:");
int a=19/0;
}     
catch(ArithmeticException e){
System.out.println(e);}//one try block with catch closed


try
{
int arr[]=new int[4];
arr[5]=19;
}
      catch(ArrayIndexOutOfBoundsException e){
      System.out.println(e);}  //another try with catch closed




catch(Exception e){
System.out.println(e);}
finally
{
System.out.println("finally block");
}
}
}

OUTPUT:
                welcome to Nested_Try block:
                java.lang.ArithmeticException:/by zero
                  java.lang.ArrayIndexOutOfBoundsException:5
                  finally block

4)THROW:

  How to Throw Exceptions:

Before you can catch an exception, some code somewhere must throw one. Any code can throw an exception: your code, code from a package written by someone else such as the packages that come with the Java platform, or the Java runtime environment. Regardless of what throws the exception, it's always thrown with the throw statement.

As you have probably noticed, the Java platform provides numerous exception classes. All the classes are descendants of the Throwable class, and all allow programs to differentiate among the various types of exceptions that can occur during the execution of a program.

You can also create your own exception classes to represent problems that can occur within the classes you write. In fact, if you are a package developer, you might have to create your own set of exception classes to allow users to differentiate an error that can occur in your package from errors that occur in the Java platform or other packages.

You can also create chained exceptions. For more information, see the Chained Exceptions section.

The throw Statement

All methods use the throw statement to throw an exception. The throw statement requires a single argument: a throwable object. Throwable objects are instances of any subclass of the Throwable class. Here's an example of a throw statement.


class ThrowDemo
{
ststic void f1()
{
try
{
throw new NullPointerException("demo");
}catch(NullPointerException e)
{       System.out.println("caught inside f1()");
throw e;//rethrow the exception
}
}

public static void main(String args[])
{
try{
f1();
}catch(NullpointerException e)
{
 System.out.println("Recaught:"+e);
}
}
}
OUTPUT:
              caught inside f1()
               Recaught: java.lang.NullPointerException: demo
//throw example program
class Throw_Demo2
{
static void f1(int num)
if(num%2!=0)
throw new ArithematicException("not a even");
else
 System.out.println("even");
}
public static void main(String args[])
{
f1(131);
}
}

5)THROWS:
                     The throwskeyword is used to declare an exception it gives an 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.

SYNTAX:
                 void method_name() throws exception_class_name
{
....
}

//sample program using THROWS
import java.io.IOException;
class A
{
void f1() throws IOException
{
throw new IOException("DEVICE ERROR");//this is CHECKED EXCEPTION
}
void f2() throws IOException
{
f1();
}
void f3()
{
try
{
f4();
}catch(Exception e)    {    System.out.println("exception handled:");    }
}
public static void main(String args[])
{
A o1=newA();
o1.f3();
System.out.println("normal flow");
}
}

OUTPUT:
                exception handled
                normal flow