Wednesday, August 2, 2023

Java Exception Handling

 

              Exception Handling

 

Exceptions can be generated by the java run-time system.Java Exception handling is managed via five keywords: try,catch,throw,throws, finally

This is the general form of an exception-handling block:

try {

        //block of code to monitor for errors

}

catch(Exception Type1 exOb) {

        //exception handler for Exception type1

}

catch(Exception Type2 exOb) {

        //exception handler for Exception type2

}

// …

finally {

        //block code to be executed before try block ends

}


Uncaught Exception

class ExcO {

     public static void main(String args[]) {

          int d =0;

          int a =42/d;

        }

}

 

Java.lang.ArithmeticException:/by Zero

                    At exc0.main(exc0.java:4)

Using try and catch

Example

File name: TryDemo.java

class TryDemo

{

        public static void main(String args[])

      {

                 int d=0;

                 int a;

                 try {   // monitor a block of code.

                      a= 42 / d;

                      System.out.println("This will not be printed");

              }catch (ArithmeticException e)

              {   //catch divide-by-zero error

                 System.out.println("Division by Zero");

               }

                 System.out.println("After catch statement");

            }

}

The output appears as given below:


 

Multiple catch clauses

Example

File name: MutipleCatch.java

class MutipleCatch {

         public static void main(String args[]) {

           try  {

                     int a =args.length;

                    System.out.println("a = " +a);

                    int b=42/a;

                    int c[] ={1};

                    c [42] = 99;

            }catch(ArithmeticException e)  {

                 System.out.println("Exception Occurred:"+e);

           }catch(ArrayIndexOutOfBoundsException e)  {

                 System.out.println ("Exception Occurred:"+e);

            }

              System.out.println("After try/catch blocks.");

          }

}

 

The output appears as given below:


C:\java MultiCatch

A=0

Divide by 0:java.lang.ArithmeticException: / by zero

After tey/catch blocks.

 

C:\java MultiCatch TestArg

A=1

Array index oob: java.lang.ArrayIndexOutOfBouundsException: 42

After try/catch blocks.

 

Example

/*This program contains an error.

A subclass must before its superclass in a series

 of catch statement. if not, unreachable code will be created and a compile-time error will result.

*/

class SuperSubcatch  {

     public static void main(String args[])  {

         try   {

                    int a=0;

                    int b=42/a;

                }

               catch(Exception e)    {

                       System.out.println("Generic Exception catch.");

              }

              /*This catch is never reached because ArithmeticException is a subclass of Exception. 

              catch(ArithmeticException e)  {//ERROR - unreachable

               System.out.println("This is never reached") ;

                 }  */

         }

}

Output


 

Throw

Throw ThrowableInstance;

//demonstrate throw

/*Program to illustrate throw clause*/

File name: ThrowDemo.java

import java.io.*;

class ThrowDemo

{

             public static void main(String args[]) throws Exception

          {

                int number=15;

                 try

               {

                  if(number>10)

                  throw new Exception("Maximum limit is 10");

              }

              catch(Exception e)

             {

                   System.out.println("Exception has been Occured"+e.toString());

            }

            finally

          {

              System.out.println("This is the last statement");

           }

       }

}

 

OUTPUT(java ThrowDemo 20)(success)



File name:    ThrowDemo.java                                           

import java.io.*;

class ThrowDemo

{

             public static void main(String args[]) throws Exception

          {

                int number=Integer.parseInt(args[0]);

               

                 try

               {

                  if(number>10)

                  throw new Exception("Maximum limit is 10");

              }

              catch(Exception e)

             {

                   System.out.println("Exception has been Occured"+e.toString());

            }

            finally

          {

              System.out.println("This is the last statement");

           }

       }

}

Output

 


Throws

File name: ThrowsDemo.java

class ThrowsDemo{

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

System.out.println("inside main");

int a=0;

int j=40/a;

System.out.println("This statement is not printed");

}

}


Output


Finally

Finally creates a block of code that will be executed after a try/catch block has completed and before the code following the try/catch block.

File name: FinallyDemo.java

class FinallyDemo{

static void procA(){

try{

System.out.println("inside procA");

throw new RuntimeException("demo");

}finally{

System.out.println("procA's finally");

}

}

static void procB(){

try{

System.out.println("inside procB");

return;

}finally{

System.out.println("procB's finally");

}

}

static void procC(){

try{

System.out.println("inside procC");

}finally{

System.out.println("procC's finally");

}

}

public static void main(String args[]){

try{

procA();

}catch(Exception e){

System.out.println("Exception caught");

}

procB();

procC();

}

}

Output

 


0 comments:

Post a Comment