Java, .NET, PHP, PYTHON, ANGULAR, ML, Data Science, Testing, CI Tutorials in Easy Languages.

"Best Software Training, Internship, Project Development center of Indore India, Helpline 780506-3968"

Exception handling Concept in Java:-
.......................................................................................................................

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 protected 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 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";

      }

}




Post a Comment

If you have any doubt in programming or join online classes then you can contact us by comment .

Previous Post Next Post