1. Computing

On Handling Exceptions in Delphi Exception Handling

How To And What Happens When You Handle Exceptions

By

No code is error free! Some code is full of "errors" on purpose :)

What's an error in an application? An error, from my general point of view, is, for example, the wrongly coded solution to a problem. Such are logic errors that could lead to wrong function results where everything seems nicely but the result of the application is completely unusable (i.e. wrong).

With logic errors, application might or might not stop working.

An exception is an exceptional condition. Exceptions include errors in your code where you try to divide numbers with zero, or you try using freed memory blocks or you try providing wrong parameters to a function.

An exception in an application is not always an error - if by error we think on those nasty problems with the program where it stop responding.

Exceptions And The Exception Class

As stated, exception are special conditions that require special handling. When an error-type condition occurs the program raises an exception.

As suggested by Nick Hodges in Exception Handling for Fun and Profit article, application writers should trap exceptions, exceptions get raised by components and library code on purpose.

You (as the application writer) handle exceptions, to make your application more error-prone, to respond to the exceptional condition.

In most cases you will find yourself being the application writer and also the library writer. So you would need to know how to raise exceptions (from your library) and how to handle them (from your application).

I'm sure we all have dozens of units defining some special-to-me classes, interfaces and alike. For example, I have a class dealing with PDF documents I'm using in several of my applications. When I code / edit the class I am the library writer, when I'm using the library I'm the application writer.

Let's take a look at handling exceptions...

The article Handling Errors and Exceptions provides some basic guidelines on how to guard against errors using try/except/end and try/finally/end protected blocks to respond to or handle exceptional conditions.

A simple try/except guarding blocks looks like:

try
  ThisFunctionMightRaiseAnException();
except
  //handle any exceptions raised in ThisFunctionMightRaiseAnException() here
end;
The ThisFunctionMightRaiseAnException might have, in its implementation, a line of code like
raise Exception.Create('special condition!');
The Exception is a special class (one of a few without a T in front of the name) defined in sysutils.pas unit. The SysUtils unit defines several special purpose Exception descendants (and thus creates a hierarchy of exception classes) like ERangeError, EDivByZero, EIntOverflow, etc.

In most cases the exceptions that you would handle in the protected try/except block would not be of the Exception (base) class but of some special Exception descendant class defined in either the VCL or in the library (you or some other developer coded) you are using.

Handling Exceptions Using Try/Except

To catch and handle an exception type you would construct a "on type_of_exception do" exception handler. The "on exception do" looks pretty much like the classic case statement:
try
  ThisFunctionMightRaiseAnException;
except
  on EZeroDivide do
  begin
    //something when dividing by zero
  end;
  on EIntOverflow do
  begin
    //something when too large integer calculation
  end;
  else
  begin
    //something when other exception types are raised
  end;
end;
Note that the else part would grab all (other) exceptions, including those you know nothing about. In general, your code should handle only exceptions you actually know how to handle and expect to be thrown.

Also, you should never "eat" an exception:

try
  ThisFunctionMightRaiseAnException;
except
end;
Eating the exception means you do not know how to handle the exception or you do not want users to see the exception or anything in between.

When you handle the exception and you need more data from it (after all it is an instance of a class) rather only the type of the exception you can do:

try
  ThisFunctionMightRaiseAnException;
except
  on E : Exception do
  begin
    ShowMessage(E.Message);
  end;
end;
The "E" in "E:Exception" is a temporary exception variable of type specified after the column character (in the above example the base Exception class). Using E you can read (or write) values to the exception object, like get or set the Message property.

Who Frees The Exception?

Noticed how exceptions are actually instances of a class descending from Exception? The raise keyword throws an exception class instance. You know that what you create (the exception instance is an object) you also need to free.

If, you as a library writer, create an instance, will the application user free it? Or, who will?

Delphi magic: handling an exception automatically destroys the exception object. This means that when you write the code in the "except / end" block - this block (hm, bad wording) will release the exception memory.

So what happens if ThisFunctionMightRaiseAnException actually raises an exception and you are not handling it (this is not the same as "eating" it)?

How Come My App Does Not Crash When number/0 Is Not Handled?

When an unhandled exception is thrown in your code, Delphi "magically" handles your exception by displaying the error dialog to the user. In most cases this dialog will not provide enough data for the user (and finally you) to understand the cause of the exception.

This is controlled by Delphi's top level message loop where ALL exceptions are being processed by the global Application object and its HandleException method.

To handle exceptions globally, and show your own more-user-friendly dialog, you can write code for the TApplicationEvents.OnException event handler.

Note that the global Application object is defined in the Forms unit. The TApplicationEvents is a component you can use to intercept the events of the global Application object.

Ok, that's it for now. Next time I'll go into reraising exception.

©2014 About.com. All rights reserved.