Exceptions


Exceptions are used to implement error handling. Exceptions are represented by classes.

Exception handling is implemented through the following three keywords:

  1. try,
  2. catch and
  3. throw.

Program statements that are to be monitored are contained within a try block. If an exception occurs in the try block it is thrown. To throw an exception the generic keyword throw is used. At the end of each try block is a catch clause. The catch clause catches exceptions that are thrown within the try block. Once caught, the exception is passed to a handler specified by the catch clause and the exception is then said to be handled.

Using try and catch

The general form of a try-catch block is shown below.

try
 {
   //.... block of code
 }
catch
{
 // .... handler for exceptions
}

The value that is caught is specified as the "exception" keyword.

Most often strings are thrown and caught. For example, consider the following program.

exception_a()
{
   try
   {
      throw "hello world"
   }
   catch
   {
      exception.println()
   }
}

This program prints "hello world" as expected.

The next program demonstrates how to throw a custom exception class.

class exception_data
{
 s
  
  exception_data(str)
  {
    s = str
  }

  println()
  {
    s.println()
  }
}

exception_b()
{
   try
   {
      throw new exception_data("hello world")
   }
   catch // catches all but rethrows everything exept exception_data.
   {
      choose exception.type()
      {
        "exception_data"
          exception.println()
        default
         throw exception
      }
   }
}

In the handler, the keyword exception in this case denotes an instance of the class exception_data. The class exception_data has a method println(), which merely prints the string it contains to the console. The method println() is called by the handler.

Note the use of the method type() to determine the type of the exception that was thrown. All exceptions other than exception_data are rethrown. Note that type() is an implicit method of all classes.