Exception handling Concept in Java?

12
It is used to handle unexpected runtime errors of the program because if the runtime error of a particular program will not be handled then the complete software system will be interrupted.
The exception is not the actual solution of program logic, it is used to protect the interruption of the program.
The compile-time error can not be handled by exception.
Throwable is the base class of Exception, it has two Subclass Error and Exception.


Type of Exception:-

1)  Checked Exception:-
This type of exception is based on predefined classes and methods of Java, if we use a particular class in the Java program then the checked exception will be automatically called.
It is mandatory to define under program code to successfully compilation and execution of Java program.
for example, if we create a File handling program then IOException is mandatory to handle during the file handling program.
 It is also called the pre-intimated exception of the Java program.
CHECKED means Check exception classes at compile time to protect runtime problems.
1 IOException   for File Handling
2 SQL Exception  for JDBC
3 ClassNotFoundException  for JDBC
4 InterruptedException  for Thread
5 ServletException   for Servlet
checked exception always will be handled by throws keyword under method.
public void writeFile() throws IOException
{
       FileWriter obj = new FileWriter();
}
2) Unchecked Exception : 
This type of exception will be raised by user input, it is not mandatory for a program without exception block program will successfully compile and execute.
all logical programs can throw unchecked exceptions according to user input.
for example, if we create an addition to the program and the user will input alphabets in place of number then the number format exception will throw.
name of unchecked exception:-
1)  NumberFormatException
2) ArrayIndexOutOFBoundsException
3)  NullPointerException
4) InputMismatchException
5) ArithmeticException
etc.
How we can handle all these types of exception:-
1)  using try-catch
    try:--   it is used to define program code which will be a throw runtime error
   catch:-  Exception Class and an Error message will be defined under catch block
   try
   {
   }
  catch(Exception ex)
  {
  }
2 try--catch--finally:-
    finally:-   this is the default block which will be executed with try or catch both.
   try
  {
  }  
  catch(Exception ex)
  {
  }  
  finally
  {
  }
Example of Exception Program:-
class Division
{
     public static void main(String args[])
     {
          int a=10,b=0,c;
          try
          {
          c=a/b;
          System.out.println(c);
          }
          catch(Exception ex)
          {
              System.out.println(ex.getMessage());
          }
          c=a+b;
          System.out.println(c);
     }
}
  
Example 2:-
import java.util.*;
class Division
{
     public static void main(String args[])
     {
          Scanner sc = new Scanner(System.in);
          int a=0,b=0,c=0;
       
          try
          {
          System.out.println("Enter first number");
          a=sc.nextInt();
          System.out.println("Enter second number");
          b=sc.nextInt();
          c=a/b;
          System.out.println(c);
          }
          catch(Exception ex)
          {
              System.out.println(ex.getMessage());
          }
          c=a+b;
          System.out.println(c);

     }
}


Example 3:-

import java.util.*;
class Division
{
     public static void main(String args[])
     {
          Scanner sc = new Scanner(System.in);
          int a=0,b=0,c=0;
       
          try
          {
          System.out.println("Enter first number");
          a=sc.nextInt();
          System.out.println("Enter second number");
          b=sc.nextInt();
          c=a/b;
          System.out.println(c);
          }
          catch(ArithmeticException ex)
          {
              System.out.println("denominator should not be zero");
          }
          catch(InputMismatchException ex)
          {
             System.out.println("enter only numeric value");
          }
          c=a+b;
          System.out.println(c);

     }
}


Example 4:-

import java.util.*;
class Division
{
     public static void main(String args[])
     {
          Scanner sc = new Scanner(System.in);
          int a=0,b=0,c=0;
       
          try
          {
          System.out.println("Enter first number");
          a=sc.nextInt();
          System.out.println("Enter second number");
          b=sc.nextInt();
          c=a/b;
          System.out.println(c);
          }
          catch(ArithmeticException ex)
          {
              System.out.println("denominator should not be zero");
          }
          catch(InputMismatchException ex)
          {
             System.out.println("enter only numeric value");
          }
          finally
          {
          c=a+b;
          System.out.println(c);
          }
     }
}


Example 6:-

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

The example which contains all possible exception:-

package scsbranch1;
import java.util.*;
public class ExceptionDemo {

public static void main(String[] args) {
try
{
int arr[] = {1,2};
System.out.println(arr[3]);
Scanner sc=null;
int a,b,c;
System.out.println("Enter first number");
a = sc.nextInt();
System.out.print("Enter second number");
b=sc.nextInt();
c=a/b;
System.out.println(c);
}
catch(InputMismatchException ex)
{
System.out.println("Invalid Input");
}
catch(ArithmeticException ex)
{
System.out.print("Denominator can not be zero");
}
catch(NullPointerException ex)
{
System.out.println("Create Object");
}
catch(ArrayIndexOutOfBoundsException ex)
{
System.out.println("Enter proper index");
}
}
Another Example of Exception using User Define Function:-

import java.util.*;
class DivException
{
  Scanner sc = new Scanner(System.in); 
   void division()
   {
       try
       {
       int a=10,b=0,c;
       System.out.println("Enter first number"); 
       a=sc.nextInt();
       System.out.println("Enter second number");
       b=sc.nextInt();
       c=a/b;
       System.out.println(c);
       }
       catch(ArithmeticException o)
       {
          System.out.println("denominator should not be zero");
       }
       catch(InputMismatchException o)
       {
          System.out.println("enter only numeric value");
       }

   }

  public static void main(String args[])
  {
      DivException obj = new DivException();
      obj.division();

  }
}

Throw keyword in exception:-

It is used to call the exception class manually, it is used to handle logical exceptions in the program.

By default try block use the throw keyword internally to call catch block.

for example, if we call ArithmeticException when users enter a negative value.

class Throwexample
{
   public static void main(String args[])
   {
       int num=-5;
       try
       {
        if(num<0)
         throw new ArithmeticException();
        System.out.println(num);
       }
       catch(ArithmeticException ex)
       {
          System.out.println("enter only positive number");
       }
   }
}

Note:-  throw keyword is mostly used to call User-defined exception in the program.

User-define Exception:-

If we create an exception class manually to extend RuntimeException then it is called User-define exception.

class Classname extends RuntimeException
{
        public String getMessage()
        {
              return "message";
       }
}

Example of User define exception with a throw?

class Throwexample
{
   public static void main(String args[])
   {
      
        int num=-5;
       try
       {
        if(num<0)
         throw new NegativeNumberException();
        System.out.println(num);
       }
       catch(NegativeNumberException ex)
       {
          System.out.println(ex.getMessage());
       }
   }
}

class NegativeNumberException extends RuntimeException
{
      public String getMessage()  
       {
           return "enter the only positive number";

      }

}
Tags

Post a Comment

12Comments

POST Answer of Questions and ASK to Doubt

  1. Command Line Input With Exception Block?

    class Division
    {
    public static void main(String args[])
    {
    int a,b,c=0;
    try
    {
    a = Integer.parseInt(args[0]);
    b = Integer.parseInt(args[1]);
    c = a/b;

    }

    catch(NumberFormatException obj)
    {
    System.out.println("Enter only numeric value");
    }
    catch(ArrayIndexOutOfBoundsException obj)
    {
    System.out.println("Pass two parameters");
    }
    catch(ArithmeticException obj)
    {
    System.out.println("denominator should not be zero");
    }
    finally
    {
    System.out.println("Result is "+c);
    }


    }


    }

    ReplyDelete
  2. Khushboo Sendre

    package Exception;

    public class Division1
    {

    public static void main(String[] args)
    {
    int a=10,b=0,c;
    try
    {
    c=a/b;
    System.out.println(c);
    }
    catch(Exception ex)
    {
    System.out.println(ex.getMessage());
    }
    c=a+b;
    System.out.println(c);
    }
    }

    ReplyDelete
  3. User define exception for less salary?

    class ExceptionExample
    {
    public static void main(String args[])
    {
    try
    {
    int sal=5000;
    if(sal<10000)
    {
    throw new SalaryException();
    }
    System.out.println("Salary is "+sal);
    }
    catch(SalaryException ex)
    {
    System.out.println(ex.getMessage());
    }

    }

    }

    class SalaryException extends RuntimeException
    {
    public String getMessage()
    {
    return "Salary should be above 10000";
    }
    }

    ReplyDelete
  4. class ExceptionExample
    {
    public static void main(String args [])
    {

    try
    {
    int sal=5000;
    if(sal<10000)
    {
    throw new SalaryException();
    }
    System.out.println("Salary is "+sal);
    }
    catch(SalaryException ex)
    {
    System.out.println(ex.getMessage());
    }

    }

    }

    class SalaryException extends RuntimeException
    {
    public String getMessage()
    {
    return "Salary should be above 10000";
    }

    }

    ReplyDelete
  5. #Example

    import java.util.InputMismatchException;
    import java.util.Scanner;
    public class AdditionExample {
    void display()
    {

    }
    public static void main(String[] args) {
    String s="";
    try
    {
    int a,b,c;
    Scanner sc = new Scanner(System.in);
    System.out.println("Enter First Number");
    a = sc.nextInt();
    System.out.println("Enter Second Number");
    b = sc.nextInt();
    c=a/b;
    System.out.println("Result is "+c);
    s= "success";
    try
    {
    System.out.println("Enter First Number");
    a = sc.nextInt();
    System.out.println("Enter Second Number");
    b = sc.nextInt();
    c=a+b;
    System.out.println("Result is "+c);
    }
    catch(Exception ex)
    {
    System.out.println(ex.getMessage());
    }
    }

    catch(InputMismatchException ex)
    {
    s= "error";
    //System.out.println(ex.getMessage());
    System.out.println("Enter only numeric value");
    }
    catch(ArithmeticException e)
    {
    s = "error";
    // System.out.println(e.getMessage());
    System.out.println("denominator can not be zero");
    }
    finally
    {
    System.out.println("Finally "+s);
    }
    try
    {
    int arr[] = {1,2};
    AdditionExample st = null;
    st.display();
    System.out.println(st);
    System.out.println(arr[1]);
    }
    catch(ArrayIndexOutOfBoundsException ex)
    {
    System.out.println("array index out of bounds ");
    //System.out.println("Error"+ex.getMessage().toString());
    }
    catch(NullPointerException ex)
    {
    System.out.println("define null value ");
    //System.out.println("Error"+ex.getMessage().toString());
    }
    }

    }

    ReplyDelete
  6. //yogesh seroke
    //try-catch-catch

    import java.util.*;
    class TryCatch1
    {
    Public static void main(String args[])
    {
    Scanner sc=new Scanner(System.in);

    try
    {
    System.out.println("enter first number... ");
    int a=sc.nextInt();
    System.out.println(" enter second number....") ;
    int b=sc.nextInt();
    int c;

    c=a/b;
    System.out.println(c);
    }

    catch(ArithmeticException ex)
    {
    System.out.println("denominator should not be zero");
    }
    catch(InputMismatchException ex)
    {
    System.out.println("enter only numeric value");
    }
    }
    }

    ReplyDelete
  7. //yogesh seroke
    //try-catch-finally

    import java.util.*;
    class TryCatchFinally
    {
    public static void main(String args[])
    {
    Scanner sc = new Scanner(System.in) ;

    try
    {
    System.out.println("enter first number...");
    int a=sc.nextInt();
    System.out.println("enter second number...");
    int b=sc.nextInt();
    int c=a/b;
    System.out.println(c);
    }
    catch(ArithmeticException ex)
    {
    System.out.println("denominator should not be zero");
    System.out.println("this is catch1 block");
    }
    catch(InputMismatchException ex)
    {
    System.out.println("enter only numeric value");
    System.out.println("this is catch2 block");
    }
    finally
    {
    System.out.println("this is finally block");
    }
    }
    }

    ReplyDelete
  8. //yogesh seroke
    //try-catch using cmd input

    class Trycatch2
    {
    public static void main(String args[])
    {
    int a, b, c;

    try
    {
    a=Integer.parseInt(args[0]);
    b=Integer.parseInt(args[1]);
    c=a/b;
    System.out.println(c);
    }
    catch(Exception ex)
    {
    System.out.println(ex.getMessage());
    }
    }
    }

    ReplyDelete
  9. //yogesh seroke
    //AllpossibleException

    import java.util.*;
    class AllpossibleException
    {
    public static void main(String args[])
    {
    try
    {
    int arr[]={1,2};

    System.out.println(arr[3]);

    Scanner sc=null;

    int a, b, c;

    System.out.println("enter first number");

    a=sc.nextInt();

    System.out.println("enter second number");

    b=sc.nextInt();

    c=a/b;

    System.out.println(c);
    }
    catch(InputMismatchException ex)
    {
    System.out.println("Invalid input");
    }
    catch(ArithmeticException ex)
    {
    System.out.println("denominator should be zero");
    }
    catch(NullPointerException ex)
    {
    System.out.println("Create Object");
    }
    catch(ArrayIndexOutOfBoundsException ex)
    {
    System.out.println("Enter proper index");
    }
    }
    }

    ReplyDelete
  10. //yogesh seroke
    //throw keyword

    class Trycatch3
    {
    public static void main(String args[])
    {
    try
    {
    int a=-5;
    if(a<0)
    {
    System.out.println(a);
    throw new ArithmeticException();
    }
    }
    catch(ArithmeticException ex)
    {
    System.out.println("put only positive number ");
    }
    }
    }

    ReplyDelete
  11. //yogesh seroke
    //user define exception

    import java.util.Scanner;

    class NegativeNumberException extends RuntimeException
    {
    public String getMessage()
    {
    return "put only positive number";
    }
    }

    class Trycatch4
    {
    Public static void main(String args[])
    {
    Scanner sc=new Scanner(System.in);
    try
    {
    System.out.println("enter number");
    int a=sc.nextInt();
    if(a<0)
    {
    System.out.println(a);
    throw new NegativeNumberException() ;
    }

    }
    catch(NegativeNumberException ex)
    {
    System.out.println(ex.getMessage());
    }
    }
    }

    ReplyDelete
  12. //SANTOSH KUMAR PAL
    //The example which contain all possible Exception.
    package exceptionhandlingconcept;

    import java.util.InputMismatchException;
    import java.util.Scanner;

    public class ExceptionDemo {

    public static void main(String[] args) {
    try
    {
    int arr[]= {1,2};
    System.out.println(arr[2]);
    Scanner sc=new Scanner(System.in);
    int a,b,c;
    System.out.println("Enter First Number");
    a=sc.nextInt();
    System.out.println("Enter Second number");
    b=sc.nextInt();
    c=a/b;;
    System.out.println(c);
    }
    catch(InputMismatchException ex)
    {
    System.out.println("Invalid Input");
    }
    catch(ArithmeticException ex)
    {
    System.out.println("Denominator should not be zero");
    }
    catch(NullPointerException ex)
    {
    System.out.println("Creat Object");
    }
    catch(ArrayIndexOutOfBoundsException ex)
    {
    System.out.println("Enter Proper Index");
    }
    }

    }

    ReplyDelete
Post a Comment