ADS

Friday 1 November 2019

Exception Handling in Java

Exception Handling:

During execution of a program some abnormal conditions might be occurring due to these abnormal conditions running program might be terminated suddenly.
If program will not be able to handle these abnormal condition then these abnormal condition will be converted into errors.
Due to this error in this case execution of the program will be terminated. But if program will be able to handle these abnormal conditions, then this abnormal condition converted into exception. And this process is called Exception Handling.
JVM is responsible to convert abnormal condition into exception.


Exception Object:

In java everything is represented in the form of object. So exception will also be represented in the form of object.
These objects will be created by JVM. Following Classes are available in java Library to create exception object.

Throwable class classification
Throwable Class Classification


Activities in exception handling classes:

     1.    Creating Exception Object:

when JVM encounters an abnormal condition JVM convert it into an exception. In this case JVM create an object of corresponding exception class ( such as Arithmetic Exception, Null Pointer Exception, IO Exception etc )

    2.    Throwing exception object:

after creating exception object JVM throws that object towards the program to catch it so that information is store in that object can be show to the user. This process is also known as raising exception.

   3.    Catching exception object:

  this is the process in which exception object is caught by the running program for this we need to write exception handling code inside the program. This code is known as “Exception Handler”.
if running program does not have exception handler or matching exception handler. Then exception object will take a U turn and in this case exception object will catch by JVM and information store in that object will be shown to the user but program will be terminated.

    What is Throwable Class:

This is top most class in the hierarchy of exception.
It is super class of all errors and exception. JVM create and throws object of throwable class ( or one of its subclass) it has following two Childs.

1.    Error Class:
JVM create and throws an object of error class for those abnormal conditions that can not be handle by the program.
it means object of this classes can not be caught.
2.    Exception Class:
JVM creates and throws an object of exception class for those abnormal condition that can be handled by the program.

Some Common Exception:

1 Arithmetic exception:

This exception is throws when a number is divide by zero.
Example:

public class JavaExceptionExample{  
  public static void main(String args[]){  
   try{  
      //code that may raise exception  
      int data=100/0;  
   }catch(ArithmeticException e){System.out.println(e);}  
   //rest code of the program   
   System.out.println("rest of the code...");  
  }  
}  


  2 Array Index out of Bound exception:
This exception is raised when an attempt is made to access array elements beyond the element of array.


class AA
{ public static void main(String[] args)
       {     int []num={8,10,20,30};
      System.out.Println(num[4]);
         }
}

3 NullPointerException:
This Exception is raised when an object will be used without allocating memory for it.

public class JJ{  
  public static void main(String args[]){
String s=null;  
System.out.println(s.length());//NullPointerException
}}


4 ClassCastException:
This exception is thrown when down casting of the object has been done into wrong child.
Example:

Class A{
}Class B extends A{
}Class C extends A{
}Class BB{
Public static void main (String []args)
{A obj=new B();
C obj2=(C) obj; //down casting
}}


 Putting Handler:

This is the process in which exception object has been caught by the running program in this case program has written following block to catch the exception object.

    1.    Try Block:

in this block exception showing statement should be written It means those statement of the method that might throw the exception should be guard in this try block.
Try block must used with at least one catch and one finally block

2. Catch Block:

Just immediately after the try block we need to write catch block. This block is responsible to catch the exception which is thrown by the statement written inside the try block.
catch block must define an argument to store the reference of exception object . every try block must have at least on catch block.
if try block statement does not throw any exception then catch block is not executed.


Class Exp{
public static void main(String[]args)
{
            System.out.print(“exception begins”);
           Try{
int res=integer.parseInt(args[0])/integer.ParseInt(args[1]);
}
catch(ArithmeticException ex)
{
System.out.Print(“Arithmetic exception caught”);
}
catch(ArrayIndexOutofBoundException ex)
{
System.out.print(“Array index out of bound exception”);
}
ex.printstacktrace();
catch(NumberFormatException ex)
{
System.out.print(“Number format exception”);
}
System.out.print(“Exception ends”);
}}

Finally Block:

Finally block is always executed where an exception is throw or not whether an exception is handled or not. So those state that you want to execute any how should be written in finally block.
Finally block cannot be use without try or catch.
Syntax:
try………catch
try……..finally
try………catch…………..finally



Exception Types:

     1.    Checked Exception
     2.    Unchecked Exception

1 Checked Exception:

Those exceptions that cannot be prevented are known as checked exception. If any statement can throw this exception then for that statement exception handler is mandatory compiler will force you to put exception handler.
These exceptions are generally occur when application uses system resources it means those statement that are using system resources (such as file ,database, network etc) might be raised checked exception.
Note: Except runtime exception and errors all other exception are checked exception.

2-Unchecked Exception:

Those exceptions that can be prevented are known as unchecked exception. Compiler will not force you to put handler for these exception because by using if condition these exception can be prevented.
Runtime exception and error are unchecked exception.

Throw Statement:

This statement should be written throw exception object explicitly this should be done whenever you want to define your own abnormal condition.
Example:

Class voter
{
Int age;
public voter(int age)
{
This.age=age;
}
public boolean checkage()
{
if(age<18)
throw new ArithmeticException(“voter not eligible”);
else
Return true;
}
}


 Custom Exception:

We can also define exception classes these class are known as custom exception parent of these classes must be throwable class is the directly or indirectly.
Example:

Class InvalidVoterException extends RuntimeException
{
Public InvalidVoterException(){}
Public InvalidVoterException(String message)
{ Super(message);
}}

 

Throws Statement:

If a statement in a method is throwing checked exception and you do not want to put handler in that method then you need to forward that exception to the calling chain means caller method. This can be achieved by using throws statement.
Note: if you calling a method which has throws statement (for checked exception) then compiler will force you to put handler or to use throws statement.



Thank You For coming ....

Subscribe for more:
www.youtube.com/coderbaba

No comments:

Post a Comment

Popular Posts