stu nicholls dot com | menu - Professional dropdown #3

click here


Exception Handling

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:

Exceptions:

Exception Object:

Advantages

Exceptions are classified into 2 categories:

Runtime Exception

Other Exception

Syntax of Exception Handling Code

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

Catching Exceptions


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

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;
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();
  }
}

Our aim is to provide information to the knowledge seekers. 

comments powered by Disqus
click here
Footer1