Skip to main content

Exception Handling

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.














 








Comments

Popular posts from this blog

Uncontrolled form input in React-JS

  Uncontrolled form input in React-JS? If we want to take input from users without any separate event handling then we can uncontrolled the data binding technique. The uncontrolled input is similar to the traditional HTML form inputs. The DOM itself handles the form data. Here, the HTML elements maintain their own state that will be updated when the input value changes. To write an uncontrolled component, you need to use a ref to get form values from the DOM. In other words, there is no need to write an event handler for every state update. You can use a ref to access the input field value of the form from the DOM. Example of Uncontrolled Form Input:- import React from "react" ; export class Info extends React . Component {     constructor ( props )     {         super ( props );         this . fun = this . fun . bind ( this ); //event method binding         this . input = React . createRef ();...

JDBC using JSP and Servlet

JDBC means Java Database Connectivity ,It is intermediates from Application to database. JDBC has different type of divers and provides to communicate from database server. JDBC contain four different type of approach to communicate with Database Type 1:- JDBC-ODBC Driver Type2:- JDBC Vendor specific Type3 :- JDBC Network Specific Type4:- JDBC Client-Server based Driver  or JAVA thin driver:- Mostly we prefer Type 4 type of Driver to communicate with database server. Step for JDBC:- 1  Create Database using MYSQL ,ORACLE ,MS-SQL or any other database 2   Create Table using database server 3   Create Form according to database table 4  Submit Form and get form data into servlet 5  write JDBC Code:-     5.1)   import package    import java.sql.*     5.2)  Add JDBC Driver according to database ide tools     5.3)  call driver in program         ...

JSP Page design using Internal CSS

  JSP is used to design the user interface of an application, CSS is used to provide set of properties. Jsp provide proper page template to create user interface of dynamic web application. We can write CSS using three different ways 1)  inline CSS:-   we will write CSS tag under HTML elements <div style="width:200px; height:100px; background-color:green;"></div> 2)  Internal CSS:-  we will write CSS under <style> block. <style type="text/css"> #abc { width:200px;  height:100px;  background-color:green; } </style> <div id="abc"></div> 3) External CSS:-  we will write CSS to create a separate file and link it into HTML Web pages. create a separate file and named it style.css #abc { width:200px;  height:100px;  background-color:green; } go into Jsp page and link style.css <link href="style.css"  type="text/css" rel="stylesheet"   /> <div id="abc"> </div> Exam...