Exception Handling

0
Exception:-













it is used to handle run time error of program using Predefine Exception Class. it is mostly used to provide security and protect the program interruption to execute another set of code.

JAVA has Throwable Class to Manage Exception and Error both

                        Throwable
 

        Error                              Exception
Compile Time                         Runtime


                                              1.1   Unchecked Exception
                                               1.2  Checked Exception


 

1.1 Unchecked Exception:-

  This type of exception will be raised by User Input and Program Execution. It is not mandatory in the program means without exception block program will be successfully compiled and executed.

Unchecked Exception Type:-

1 Arithmetic Exception:-  it will be raised based on an arithmetic error in the program .for example if we enter 0 to the denominator in division program then divide by zero exception is an arithmetic exception.

2 NumberFormat Exception:-  It will be raised when we enter unformatted data means in integer value if we enter String
Command-Line Input operation always throw Number Format if we pass incorrect numeric data.

int a= "hello";  //NumberFormatException


3 ArrayIndexOutOfBoundsException:-

it will be raised when we use out of index value of array means array will take 3 elements and we pass 4 element from Command Line Input of any other method

int arr[] = {11,21}
System.out.println(arr[2])



4 NullPointerException:-

If We create Instance not Object and Call a particular method or variable then Nullpointerexception will be called.

Hello obj=null;
obj.display();

5 InputmismatchException:-

It will be called when we pass incorrect input data by Scanner Input Class.

Scanner sc = new Scanner(System.in);
int a = sc.nextInt();  //hello


How we handle Unchecked Exception

try
{
    Code Section
}
catch(ExceptionClass ref)
{
    Error Section
}


....................................................................................................................
try
{
    Code Section
}
catch(ExceptionClass ref)
{
    Error Section
}
catch(ExceptionClass ref)
{
    Error Section
}

......................................................................................................................

try
{
    Code Section
}
catch(ExceptionClass ref)
{
    Error Section
}
finally
{
   Default Exception block which will be executed whenever an error will be raised or not.
    it will be used when we want to destroy the object or provide common statement
}

......................................................................................................................
try
{
    Code Section
}
finally
{
    Error Section
}



Example of Try and Catch Block for Division Program

class Division
{
    public static void main(String args[])
    {
         try
         {
         int c = Integer.parseInt(args[0])/Integer.parseInt(args[1]);
         System.out.println(c);
        }
       catch(Exception ex)
       {
         System.out.println(ex.getMessage().toString());
       }

     System.out.println("LINE1");
     System.out.println("LINE2");
     System.out.println("LINE3");

    }

}



Limitation of this program:-  it is not displaying User-Friendly Error Message.


Program using Single Try and Multiple Catch Block:-

class Division
{
    public static void main(String args[])
    {
         try
         {
         int c = Integer.parseInt(args[0])/Integer.parseInt(args[1]);
         System.out.println(c);
        }
       catch(ArithmeticException ex)
       {
         System.out.println("denominator should not be zero");
       }
        catch(ArrayIndexOutOfBoundsException ex)
       {
         System.out.println("Enter two values for division");
       }
        catch(NumberFormatException ex)
       {
         System.out.println("Enter only Integer data");
       }

     System.out.println("LINE1");
     System.out.println("LINE2");
     System.out.println("LINE3");

    }

}


Try Catch and Finally:-

class Division
{
    public static void main(String args[])
    {
         try
         {
         int c = Integer.parseInt(args[0])/Integer.parseInt(args[1]);
         System.out.println(c);
        }
       catch(ArithmeticException ex)
       {
         System.out.println("denominator should not be zero");
       }
        catch(ArrayIndexOutOfBoundsException ex)
       {
         System.out.println("Enter two values for division");
       }
        catch(NumberFormatException ex)
       {
         System.out.println("Enter only Integer data");
       }
      finally
      {
     System.out.println("LINE1");
     System.out.println("LINE2");
     System.out.println("LINE3");
     }

    }

}


Try and Finally:-

It is mostly used to handle Checked Exception of Program using Throws Keyword.

if we use in Unchecked Exception then finally statement will be executed and try will force to catch block.


class Division
{
    public static void main(String args[]) throws ArithmeticException
    {
         try
         {
         int c = Integer.parseInt(args[0])/Integer.parseInt(args[1]);
         System.out.println(c);
        }
   
      finally
      {
     System.out.println("LINE1");
     System.out.println("LINE2");
     System.out.println("LINE3");
     }

    }

}
..............................................................................................................................................
Throw :-

It is used to call exception classes explicit in the program .because all Exception Clases will be called implicit according to predefined error code.


for example if we want to call arithmetic exception when user will press negative value.

Scanner sc = new Scanner(System.in);
try

{
     int num;
     System.out.println("enter number");
    num=sc.nextInt();
   
    if(num<0)
     throw new ArithmeticException();

}

catch(ArithmeticException ex)
{
    System.out.println("Enter positive number only");
}





ASSIGNMENT:-

WAP to calculate SI using Command Line Input?

WAP to throw NumberForamat Exception When User Input Incorrect MobileNumber?

WAP to throw NumberFormat Exception when User Input Incorrect EmailId?



USER DEFINE Exception:-

using this concept we can create our own exception classes.it will always use with the throw statement.


class Classname extends RuntimeException
{
      public String getString()
      {
         return "Error Message";
      }
 

}

RuntimeException Class is used to Handle all System Define Exception and Provide System Define Error Message.

............................................................................................................................................

2 CheckedException:-


this type of exception has created for specific Classes and methods if we use these classes in Program then checked exception will be checked by the compiler if an exception is not handled then the compiler will provide the compile-time error.

it is completely different from unchecked exception because unchecked exception always will provide runtime error for incorrect input data.


CheckedException Classes

1 IOException:-     it is mandatory for File SubClasses

2  InterruptedException:-  When we use Thread.sleep() then this exception is mandatory

3 SQLException:-  When we connect data from JDBC then SQLException is common

4 ServletException:-  It will be throw by Servlet Exception

5 ClassNotFoundException:-  it will be throw by JDBC Driver Class for database Connection etc.

...................................................................................................................................................................

Checked Exception will be handled by throws keyword mostly because it is only for program execution not to provide any error message.


public static void main(String args[]) throws CheckedException
{


}

means if any CheckedException Classes is used in the program then CheckedException will be thrown by main()


import java.io.*;
class CheckedExceptionDemo
{
    public static void main(String args[]) throws IOException
    {
         System.out.println("enter char");
         int a = System.in.read();
         System.out.println((char)a);
    }

}




NOTE:- CHECKED EXCEPTION WILL BE HANDLED BY throws keyword and Try--Catch Block both but we should prefer throws keyword to handle this type of exception.



WAP to perform addition of two number using System.in.read()?

WAP to Create UserDefine Exception for InvalidMobileNumber,InvalidEmailId and InvalidUrl?

WAP to Throw Exception if Password is weak means if a password has no special char and length less then 5 then the password will be weak.














 








Post a Comment

0Comments

POST Answer of Questions and ASK to Doubt

Post a Comment (0)