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

Syntax:

try
  statement
catch
  statement

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.

space exception_a
{
    class exception_a
    {
       exception_a()
       {
           try
           {
              throw "hello world"
           }
           catch
           {
              cout << exception << "\n"
           }
        }
    }
}

This program prints "hello world" as expected.

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

using system

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

        operator string() { return s }
    }

     class exception_b
     {
        exception_b()
        {
           try
           {
               throw exception_data("hello world")
           } 
           catch
           {
               choose exception.type()
               {
                  "exception_b::exception_data"
                   cout  << exception  << "\n"

                  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 an operator that converts to string. This operator 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.