yt

Header Ads

Chapter - 18 What is Exception Handling in Java

Exception Handling in Java

Introduction of java exception handling : 

Exception एक ऐसी situation होती है जो आपके रन होते हुए program को रोक देती है। जैसे की जितनी memory आपके program को execute होने के लिए चाहिए, उतनी memory आपके computer में यदि नहीं है तो आपके program का execution रुक जायेगा। ये out of memory exception है। ऐसी ही situations को आप exceptions/ run time errors कहते है।

NOTE : EXCEPTION MEANS JO SOCHA NHI THA WAH HO GYA 

जिस प्रकार यदि आप program बनाते समय किसी statement के आगे semicolon ; लगाना भूल जाये, तो आपको program error शो करता है और compile नहीं होता है। उसी प्रकार exception generate होने पर आपका program रुक जाता है execute नहीं होता है।

यदि आप चाहते है की आपका program exception आने पर रुके नहीं execute होता रहे तो इसके लिए आपको exceptions को handleकरना होगा। इसे ही exception handling कहते है। जब आप exceptions को handle करते है तो आपका program exception आने पर रुकता Nahi है,  बल्कि exception वाले code को skip करके बाकि के code को execute करता है।

Keywords

Java में आप कुछ keywords की मदद से exceptions को handle करते है। ये सभी keywords मिलकर एक structure बनाते है जो implement करने में बहुत ही आसान होता है। इन keywords के बारे में निचे दिया जा रहा है।

Keywords Explanation Handling Uses :- 

1. Try

आपके program का वह code जो exception generate कर सकता है, उसे आप try block में लिखते है। उदाहरण के लिए आप program में कोई mathematical operation कर रहे है और  आपको लगता है की exception generate हो सकती है तो आप उस code को try block में लिखते है।

2. catch

यदि try block में कोई exception generate होती है, तो वह इसी block में handle की जाती है। आ इस block में वह code लिखते जो exception आ पर आप execute करना चाहते है। उदाहरण के लिए आप एक message print करवा सकते है जो यूजर को बताये की exception generate हुई है।


3.throw

ज्यादातर संभावित exceptions आपके लिए पहले से ही java library में define है और ये exception java automatically throw ne देती है। लेकिन यदि आप चाहते है तो खुद की exceptions भी create कर सकते है। ऐसी एक्सकेप्शन्स को आपको खुद ही throw करना होता है इसके लिए आप throw keyword यूज़ करते है। आप चाहे तो predefined exception भी throw कर सकते है।

4. Throws(Handle a particular line)  

आप nested try blocks यूज़ कर सकते है। यदि आप चाहते है की किसी exception को outer try block handle करे तो ऐसी situation में आप throws keyword यूज़ करते है। आप method में definition के आगे throws keyword लगा कर सभी exceptions के नाम लिख देते है। ऐसा करने से यदि कोई exception आती है तो outer try block उसे handle करता है।

5. Finally

Exception handle करने के बाद आप जो code execute करवाना चाहते है उसे finally block में लिखते है। Try block में exception आने के बाद compiler उस code को execute नहीं करता है और catch block के बाद सीधा finally block को execute करता है।

Steps to handle exceptions

Arithmetic Exceptions

कोई भी arithmetic error जैसे की यदि आप किसी number को zero से divide करने की कोशिश करे या फिर किसी variable में उसकी size से ज्यादा value store करने के कोशिश करे तो Arithmetic- Exception generate होती है।

Class Cast Exception

यदि आप किसी class का reference दूसरी class में store करवाना चाहते है और यदि पहली class दूसरी class की sub class नहीं होती है तो Class-Cast-Exception generate होती है।

Array Store Exception

यदि आपने string array बनाया है और उसमे आप string store करने की कोशिश करते है तो Array-Store Exception generate होती है।

Array Index Out Of Bounds Exception

यदि आपके array की size 10 है और आप 11th position पर value store करने की कोशिश करे या 11th position को access करने की कोशिश करे तो Array-Index-Out-Of-Bounds-Exception | generate होती है।

Illegal Argument Exception

जब आप किसी method में invalid argument pass करते है जैसे की int की जगह string पास कर दे तो Illegal-Argument-Exception generate होती है।

Null Pointer Exception

Java में आप किसी reference variable को null value assign कर सकते है लेकिन यदि आप इस reference variable को यूज़ करने का प्रयास करते है तो Null Pointer Exception generate होती है।

Number Format Exception

जब आप किसी string value को number में cast करने की कोशिश करते Number-Format-Exception aati hai. 

Example :- Find a simple program using  exception handling. 


// Example 1: Simple Program Exception Hadling
import java.lang.*;
class ExcHand{
    public static void main(String args[]){
        int a=49;
        // int b= 5; // Program successfully run
        int b=0; // then generate a error arthnetic exception error.
        try{
        int c= a/b;
        System.out.print("Division value of a and b:"+c);
        }
        catch(ArithmeticException e){
            System.out.println("Don't input b value is 0");
            System.out.println("You can't divided a number in to zero");
        }
    }
}


*****OUTPUT******

Before Used try and catch error : 


PS F:\Learning File\BCA\BCA 3rd Sem\JAVA OOP\BLOG> javac blog.java
PS F:\Learning File\BCA\BCA 3rd Sem\JAVA OOP\BLOG> java ExcHand  
Exception in thread "main" java.lang.ArithmeticException: / by zero
        at ExcHand.main(blog.java:1065)


After Used try and catch Solve error: 


PS F:\Learning File\BCA\BCA 3rd Sem\JAVA OOP\BLOG> javac blog.java
PS F:\Learning File\BCA\BCA 3rd Sem\JAVA OOP\BLOG> java ExcHand  
Don't input b value is 0
You can't divided a number in to zero



Introduction of java exception handling in English

To understand the exception firstly we should know about the error in program. 

Errors in program can be categorized into two types.

  1. Compile Time Errors
  2. Run Time Errors
  1. Compile Time Errors:- Errors caught during compiled time is called Compile time errors. Compile time errors include library reference, syntax error or incorrect class import.
  2. Run Time Errors:- The error that occurs during the run time of program is called run time error. They are also known as exceptions means that future error. Hence we can say that exception is a runtime error that occours because of user's mistake.

Reasons of Exception

  • Mismatched Input :Suppose that we are entering our name in place of age,causing exception because age is of data type int and name will be string.
  • File does not exist :Suppose that we are reading a text file easy.txt and that file does not exist in the system,causing exception.
  • Exception related to array :Suppose that the array size is 5 and we are inserting more than 5 elements,causing exception.
  • Divide by zero exception :When a number is divided by zero then the output will be undefined(infinity).

Exception Handling

  • The process of handling the exception is called exception handling.

There are four main keyword are used to solve the problem of exception.

  1. try block :It is the place where actual code is written and exception occours.when the code will lead to any error, that error/exception will get caught inside the catch block.
  2. catch block : catch block is intended to catch the error and handle the exception condition. We can have multiple catch blocks to handle different types of exception and perform different actions when the exceptions occur.
  3. throw statement : It is used to show the user defined message about the exception.
  4. finally block : This block executes either exception occours or does not occours.

Syntax of try-catch


try {
   // protected code
} catch( ExceptionName e1 ) {
// Statements .......
} catch( ExceptionName e2 ) {
 // Statements .......
} catch( ExceptionName eN ) {
   // Statements .......
}

Example 1:try _ catch program 


// Example :- 1 try catch used
import java.util.Scanner;
class Exptry{
    public static void main(String args[]){
        Scanner sc = new Scanner(System.in);
        // int a, b, c;
        try{
            System.out.println("Enter 1st number : ");
            int a= sc.nextInt();
            System.out.println("Enter 2nd number : ");
            int b= sc.nextInt();
            int c=a/b;
            System.out.println("Division value is : "+c);
        } catch(Exception e)
        {
            System.out.println("You can not Divied by zero number. 4,5,6,7,8,9,...");
        }
    }
}


*****OUTPUT******

 1st Run Before input 0 value


Enter 1st number : 78 Enter 2nd number : 9 Division value is : 8



2nd Run After input 0 value  


Enter 1st number : 78 Enter 2nd number : 0 You can not Divied by zero number. 4,5,6,7,8,9,....



Example 2:try _ catch _ throw program :


// Example 2:try _ catch _ throw

class Expcatch
{
 public static void main(String[] args)
 {
  Scanner obj=new Scanner(System.in);
  int a,b,c;
  try
  {
   System.out.println("Enter first number");
   b=obj.nextInt();
   System.out.println("Enter second number");
   c=obj.nextInt();
   if(c!=0)
   {
   a=b/c;
   System.out.println("Div="+a);
   }
   else
   throw  new Exception("Don't put zero in denominator");
  } catch (Exception e)
  {
   System.out.println("Error:"+e);
  }  
 }
}


*****OUTPUT******

  •  1st Run Before input 0 value


Enter first number 78 Enter second number 9 Div=8



  •  2nd Run 


Enter first number 56 Enter second number 0 Error:java.lang.Exception: Don't put zero in denominator



Example 3 :try _ catch _ throw _ finally program 


// Example 3:- try _ catch _ throw _ finally
import java.util.Scanner;
class Exptryfinally{
    public static void main(String args[]){
        Scanner sc= new Scanner(System.in);
        int a=0,b,c;
        try{
        System.out.print("Enter 1st value ");
        b= sc.nextInt();
        System.out.print("Enter 2nd value ");
        c= sc.nextInt();
        if(c != 0){
            a= b/c;
        }
        else
            throw new Exception("Dont 't put zero vaue");
        }
        catch(Exception e){
            System.out.println("Error of program"+e);
        }
        finally{
            System.out.print("Division value="+a);
        }
    }
}



*****OUTPUT******

 1st Run Before input 0 value


Enter 1st value 45 Enter 2nd value 6 Division value=7



 2nd Run 


Enter 1st value 45 Enter 2nd value 0 Error of programjava.lang.Exception: Dont 't put zero vaue Division value=0


I hope this post is helpful for learn exception handling. Don't forget follow me...




No comments

Theme images by Dizzo. Powered by Blogger.