Wednesday, September 27, 2023

Exception notes

 Exception Handling:

An exception is an abnormal condition that arises in a code sequence at run time. Exception is a run time error.

Java and other programming languages have mechanisms for handling exceptions that you can use to keep your program from crashing.  In Java, this is known as catching an exception/exception handling.

When java interpreter encounters an error, it creates an exception object and throws it( informs us that an error occurred).

If the exception object is not caught and handled properly, the interpreter will display a message and stops the program execution.

If we want the program to continue with the execution of the remaining code, then we should try to catch the exception object thrown by the error condition and then display an appropriate message for taking corrective actions.


Errors are broadly classified into two categories.

1. Compile time exception(error)

2. Run Time exception(error)


Compile-time errors:

All syntax errors will be detected and displayed by the java compiler and therefore these errors are known as compile-time errors.

Whenever the compiler displays an error, it will not create the .class file.


Run-time errors:

Sometimes a program may compile successfully creating the .class file but may not run properly because of abnormal conditions.

Common run-time errors are

o The file you try to open may not exist.

o Dividing an integer by Zero.

o Accessing an element that is out of the bonds of an array type.

o Trying to store a value into an array of an incompatiable class or type.

o Trying to cast an instance of a class to one of its subclasses.

o And many more……………..



Each exception is a class, part of java.lang package and it is derived from Throwable class.


Java Exception handling is managed by 5 keywords.

1. try

2. catch

3. throw

4. throws

5. finally


If these abnormal conditions are not handled properly, either the program will be aborted or the incorrect result will be carried on causing more and more abnormal conditions.


Example to see what happens if the exceptions are not handled:

class NoException 

{

public static void main(String[] args) 

{

int no=10;

int r=0;

r=no/0;

System.out.println("Result is:"+r);

}

}

The above program gives the following error:

Exception in thread "main" java.lang.ArithmeticException: / by zero

        at NoException.main(NoException.java:8)


In the above program the error is handled by the default exception handler which is provided by java run-time system.


If the exception is handled by the user then it gives two benefits.

1. Fixes the error.

2. Avoids automatic termination of program.


Syntax:

       try

       {

        statement;   // generates exception

       }

       catch(Exception-type e)

       {

        statement;   // process the exception

       } 

Java uses a keyword try to preface a block of code that is likely to cause an error and “throw” an exception.

A catch block is defined by the keyword catch “catches” the exception “thrown” by the exception block.

Catch block should be immediately after the try block.

try block can have one or more statements that could generate an exception.

If any one statement generates an exception, the remaining statements in the block are skipped and control jumps to the catch block that is placed next to the try block.

The catch block too can have one or more statements that are necessary to process the exception.

Every try block should be followed by at least one catch statement.

Catch statement works like a method definition, contains one parameter, which is reference to the exception object thrown by the try block.


Program:

// program name:..\atish\java_new\core\exp\TryCatch.java

class TryCatch

{

  public static void main(String[] args) 

  {

    int a=10;

    int b=5;

    int c=5;

    int r;


    try

    { r=a/(b-c); // exception here

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

    }

    catch(ArithmeticException e)

    { System.out.println("Cannot divide by 0....."); }

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

  }

}

Note: Once an exception is thrown, control is transferred to catch block and never returns to try block again.


***Statements after the exception statement(try block) never get xecuted.


Multiple catch statements:

Syntax:


try

{

 statement;

}

catch(Exception-type 1 e)

{

 statement;  // process exception type 1

catch(Exception-type 2 e)

{

 statement;  // process exception type 2

catch(Exception-type N e)

{

 statement;  // process exception type N

When an exception in a try block is generated, java treats the multiple catch statements like cases in switch statement.

The first statement whose parameter matches with the exception object will be executed, and the remaining statements will be skipped.

Code in the catch block is not compulsory.

o catch (Exception e){}

o the catch statement simply ends with a curly braces( {} ), which does nothing, this statement will catch an exception and then ignore it.


import java.util.*;


class MultiCatch

{

 public static void main(String args[])

 {

  int no,d,r;

  no=d=r=0;


 try

 {

  no=Integer.parseInt(args[0]);

  d=Integer.parseInt(args[1]);


  r=no/d;

  System.out.println("Result :"+r);

 }

 catch (NumberFormatException nf)

 {

   System.out.println(nf);

 }


catch (ArrayIndexOutOfBoundsException ai)

 {

 System.out.println(ai);

 }

 catch (ArithmeticException ae)

 {

  System.out.println(ae);

 }

 }

}


Finally:


Java supports another statement known as finally that can be used to handle an exception that is not caught by any one of the previous catch statements.

Finally block can be used to handle any exception generated with in a try block. 

It may be added immediately after the try block or the last catch block.


Syntax 1:                                    syntax 2:

try                                          try

{                                            {   

 statements;                                  statements;

}                                            }

finally                                      catch(..)

{                                            {

 statements;                                  statements;

}                                            }

                                             catch(..)

                                             {

                                              statements;

                                             }

                                             finally

                                             {

                                              statements;

                                             }

Note:

When a finally block is defined, this is guaranteed to execute, regardless whether exception is thrown or not.

Finally block is mainly used to close the files, releasing system resources.


throws clause:

Runtime Exceptions are referred to as unchecked exceptions. All other exceptions are checked exceptions, they don’t derive from java.lang.RuntimeException.

A Checked exception must be caught some where in the program code.

If you invoke a method that throws a checked exception but you don't catch the checked exception somewhere, your code will not compile. That's why they are called checked exceptions.

The compiler checks to make sure that they are handled or declared.


Syntax:


<return type> method name([parameters-list]) throws exp 1,exp 2,…………

Ex: 1

        import java.io.*;

        class ThrowsTest

        {

         public static void main() throws EOFException

         {

          throw new EOFException();

          }

         }


Ex: 2

import java.io.*;

 class Test

 {

  void doWork() throws IOException


  {

   throw new IOException();

  }

 }


 class ThrowsTest1

 {

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

  {

   Test t1=new Test();

   t1.doWork();

  }

  }



Printing information about an exception:

it is useful to discover the cause of an exception. When you know the cause of an exception, it makes easier to fix programming bugs as soon as they discovered.

As all the exception classes are derived from Throwable, they all support the following methods provided by the Throwable.


Nested try statements:

Try statements can nested.


// program name:..\atish\java_new\core\exp\NestedTry.java

class NestedTry

 {

   public static void main(String args[])

    {

     try

     {

      int a=args.length;

      int b=10/a; // if no command line argument is passed

                 // it generates divide-by-zero exception

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

      try

      {

       if(a==1)

         a=a/(a-a); // divide-by-zero exception

       else

           if(a==2)

            {

             int c[]={1};

             c[5]=99; // generates out of bounds exception

             }

        }

        catch(ArrayIndexOutOfBoundsException e)

        { System.out.println("Array index out-of-bounds:"+e); }

      }

      catch(ArithmeticException e)

      { System.out.println("Divide by 0:"+e); }

    }

  }


Rethrowing the exceptions:


class ReThrow

{

 static void test()

 {

  try

  {

   throw new NullPointerException("Testing..");

   }

  catch(NullPointerException e)

  {

   System.out.println("Caught inside test method..");

   throw e; // rethrow the exception

  }

 }


  public static void main(String args[])

  {

   try

   {

    test();

    }

   catch(NullPointerException e)

   {

    System.out.println("Recaught..:"+e);

   }

  }

 }            


Example NullPointer Exception:

class Test

{

 int no=10;

 void disp()

 { System.out.println("no is:"+no);

    }

}

class NPE

{

 public static void main(String args[])

 {

  Test t=new Test();

  t=null;

  try{

  t.disp();

  }

  catch(NullPointerException np)

  { np.printStackTrace();

    }

 }

}









No comments:

Post a Comment

Machine Learning Course Assignments 2024(Dec)

 Machine Learning Course Assignments 2024 1)   Explain the concept of "generalization" in machine learning. Why is it a central go...