Exception Handling

  • Exception and Advantages
  • Runtime Exception and Other Exception
  • Catching Exceptions
  • 'finally' clause
  • 'throws' clause
  • Throwing our own exceptions

Managing Errors and Exceptions

It is common to make mistakes at the time of developing and typing the program.Unexpected errors may be obtained because of a mistake in the program.The error may terminate the execution of the program itself.

Types of Errors

Errors may be broadly classified into two categories.

  • Compile time errors
  • Run time errors
Compile Time Errors:
  • These are nothing but syntactical errors generated at the time of compilation of the program.
Run Time Errors:
  • These are the errors generated at the time of execution of the program although the program has not generated any syntactical errors.

Exceptions:

  • An exception is a condition that is caused by a run - time error in a program. When the java interpreter encounters an error such as dividing an integer by zero, it creates an exception object and throws it. If the exception object is not caught and not handled properly, the interpreter will display the error message and will terminate the program. If we want the program to continue to 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. This task is known as exception handling.
  • Used by Java to provide error handling capabilities for its programs.
  • An event that occurs during the execution of a program that disrupts the normal flow of execution.
Exception Object:
  • When exceptional event occurs within a Java method, the method creates an exception object, hands it over to the runtime system.
  • Contains information about the exception.
  • Runtime system tries to find some code to handle.

Advantages:

  • It helps to separate the error handling code from the regular code.
  • The code becomes more robust
Exceptions are classified into 2 categories:
  • Runtime Exceptions
  • Other Exceptions

Runtime Exception:

  • within Java runtime system.
  • Since the cost of handling of these exceptions exceeds the benefit, compiler does not require you to catch or specify them .

  • Example:
  • arithmetic exceptions (divide by zero)
  • pointer exception (trying to access an object through a null ref.)
  • indexing exceptions (ref. across the array limit)

Other Exception:

  • These are checked by the compiler
  • A method must declare all the checked exceptions it throws

  • Example:
  • EOFException
  • IOException

Syntax of Exception Handling Code:

try
{
    statements;
}
catch (ExceptionType e)
{
    statements;
}

Catching Exceptions:

  • try.....catch block
  • 'try' block contains the code that might throw an exception.
  • 'catch' block contains the exception handling code.
  • For one 'try' block there may be many 'catch' blocks

Example:
public void myMethod()
{
  try
  {
    // code which may throw exceptions
  }
  catch(Exception1 e1)
  {
    // handle exception e1 here
  }
  catch(Exception e2)
  {
    // handle exception e2 here
  }
}

Example1

class ErrorCheck
{
  public static void main (String args[])
  {
    int a = 20;
    int b = 10;
    int c = 10;
    int x, y;
    try
    {
      x = a/(b-c);
    }
    catch(ArithmeticException e)
    {
      System.out.println ("Division by zero error");
    }
    y = a/(b+c);
    System.out.println("The value of y is "+y);
  }
}

Example2: Program to catch invalid command line argument.

class CmdLineArg
{
  public static void main (String args[])
  {
  int count = 0, invalid = 0;
  int i, num;
  for (i=0; i<args.length; i++)
  {
    try
    {
      num = Integer.parseInt(args[i]);
    }
    catch (NumberFormatException e)
    {
      invalid = invalid + 1;
      System.out.println("Invalid number " + args[i]);
      continue;
    }
    count = count+1;
  }
  System.out.println("Total Valid numbers = " + count);
  System.out.println("Total Invalid numbers = " + invalid);
  }
}

Multiple Exceptions

For one 'try' block there may be many 'catch' blocks
Syntax:
    .....
    try
    {
      statement1
    }
    Catch(Exception Type1 e)
    {
      statement;
    }
    Catch(Exception type2 e)
    {
      statement;
    }
      ......
    Catch(Exception type n e)
    {
      ......
    }

Program

class MultipleCatch
{
  public static void main(String args[])
  {
      int m[] = new int [2];
      int n = 10; m[0]=10; m[1]=20;
      try
      {
        int y = m[2]/(n-m[1]);
      }
      catch (ArithmeticException e)
      {
        System.out.println ("Division by zero " );
      }
      catch(ArrayIndexOutOfBoundsException i)
      {
        System.out.println("Out of array boundary");
      }
      int y=m[1]+m[0];
      System.out.println("The value of y is: " +y);
  }
}

'finally' clause

  • Optional part of try/catch block.
  • The code within this block will be executed irrespective of whether the exception is thrown or not.
  • Usually contains code for cleanup process - such as releasing resources, closing file, save process status etc.
Syntax:
try
{
  statements;
}
catch ( )
{
  statements;
}
finally
{
  statements;
}

Example
public void myMethod()
{
  try
  {
    // code which may throw exceptions.
  }
  catch(Exception e)
  {
    //handle exception e here
  }
  finally
  {
    // code for cleanup
  }
  ....
}

'throws' clause

The java language requires that methods either catch or specify or check exceptions that can be thrown in the scope of that method. The try/catch block facilitates protecting code and catching any exceptions that might occur. An alternative way is to indicate that a method may possibly throw an exception. This is done by adding the throws keyword after the signature of the method followed by the name of one or more exceptions.

e.g.:
public MyFunction( ) throws IOException
{ :: }

e.g.: public void myMethod() throws AnException
{//the code which may throw AnException}

A method can throw any number of possible exceptions.
When multiple exceptions are to be thrown, they are all put in the throws clause separated by commas.

e.g.:
public MyFunction ( ) throws IOException, ArithmeticException,....
{
.
.
.
.
}
public void myMethod() throws Exception1, Exception2, Exception3,...
{
// the code which may throw AnException
}

Throwing our own exceptions

There may be times when we like to throw our own exceptions and we do this by using the keyword throw.

Syntax:
    throw new throwable_subclass;
  • Create a class which inherit from suitable Exception class.
  • Return an object of this class in the method which throws the exception.
class MyException extends IOException
{
  public MyException()
  { . . . }
  public MyException(String s)
  {
    super(s);
    .....
  }
}
class WriteFile
{
  void writeToFile() throws IOException
  {.....
    throw new MyException("IOError");
  }
}

Programs


import java.lang.Exception;
class NewException extends Exception
{
  NewException (String message)
  {
    super(message);
  }
}
class TestNewException
{
  public static void main (String args[])
  {
    int m =5, n = 2000;
    try
    {
      float o = (float) m / (float) n;
      if(o<0.01)
      {
        throw new NewException("Very small number");
      }
    }
    catch (NewException e)
    {
      System.out.println("New exception caught");
      System.out.println(e.getMessage());
    }
    finally
    {
    System.out.println("This is closing");
     }
  }
}

import java.lang.Exception;
class NewException extends ArithmeticException
{
  NewException (String message)
  {
    super(message);
  }
}
class ThrowMyException
{
  public static void calc() throws ArithmeticException
  {
    int x=15,y=5,z=10,M;
    try
    {
      if (x==y)
      {
        throw new NewException ("Division by zero error");
      }
      M=z*(x-y);
      System.out.println("The value of M is: " +M);
    }
    catch(NewException e)
    {
      System.out.println("Caught my exception");
      System.out.println(e.getMessage());
    }
    finally
    {
      System.out.println("This is finally");
    }
  }
  public static void main(String args[])throws ArithmeticException
  {
      ThrowMyException t1 = new ThrowMyException();
      t1.calc();
  }
}


Java Classes and Methods << Previous

Next>> Java Streams

Our aim is to provide information to the knowledge seekers. 


comments powered by Disqus


Footer1