Difference between revisions of "Exception Handling"

From wiki.visual-prolog.com

m (release)
m (Typo (I to In))
Line 91: Line 91:
Many/most programmers will never need to define exceptions, because in many/most cases the exceptions to use are already defined.  An exception definition is only needed when the exception must be distinguished from other kinds of exceptions, such that exception handlers can deal specially with that kind of exception.  Typically exception definitions are only necessary for exceptions that are raised by library software.  I most cases programmers will raise the exception <vp>internal_error</vp>.
Many/most programmers will never need to define exceptions, because in many/most cases the exceptions to use are already defined.  An exception definition is only needed when the exception must be distinguished from other kinds of exceptions, such that exception handlers can deal specially with that kind of exception.  Typically exception definitions are only necessary for exceptions that are raised by library software.  In most cases programmers will raise the exception <vp>internal_error</vp>.
=== Raising an exception ===
=== Raising an exception ===

Revision as of 18:07, 8 November 2016

An exception is a deviation from the expected. What is an exception in one context may be expected in another context, and thus not an exception in that context.

In Visual Prolog programs exceptions are used to deal with deviations from what is expected in the given context. When a certain program part gets into a situation it cannot deal with it can raise an exception. When an exception is raised the program control is transferred to the nearest exception handler. If the exception handler cannot handle the exception it can either raise a new exception or continue the original exception.

The program will terminate with an error message if there is no exception handler to transfer the control to.

Introduction to exception handling

There are many concepts and entities to understand when dealing with exceptions. This section will give an introduction by means of an example.

A certain program needs to write some information to a file. Therefore it has a predicate writeInfo that can write this information. writeInfo calls the PFC constructor outputStream_file::create to obtain a stream that it can write the information to:

    writeInfo(Filename) :-
        S = outputStream_file::create(Filename),

But if the file already exists and is write-protected it is impossible to create the stream.

In outputStream_file::create this situation is considered to be exceptional/unexpected and therefore it raises an exception.

When an exception is raised the program control is transferred to the nearest exception handler, which can hopefully handle the situation and thus bring the program back on track again.

In this case writeInfo is called after the user have entered the file name in a dialog and pressed a Save-button. So the handling we want is simply to tell the user that the information was not written because the file was write-protected. The user can choose a different filename, remove the write protection, delete the file, cancel the operation entirely or something else. But from the program's point of view the exceptional situation is handled.

To set a handler we use the try-catch language construction:

    saveInfo(Filename) :-
         catch TraceId do
              % <<handle situation>>
         end try.

The code works like this: writeInfo is called, if it succeeds the try-catch construction will not do more and saveInfo will also succeed.

But in the write-protected case outputStream_file::create will raise an exception and therefore the following will take place:

  1. TraceId will be bound to the (so called) trace id, which is a handle to information about the exception (described in more details below)
  2. The handler code (i.e. the code between do and end try) is evaluated
  3. The result of the handler code will be the result of the try-catch construction, and thus of saveInfo.

So for the "write-protected" exception the handler code should write a message to the user.

If it is another kind of exception the handler will have to do something different. Especially, it may be an exception that the handler does not know how to handle. In this case the best thing the handler code can do is to continue the exception as an unknown exception (i.e. unknown to the handler).

When an exception is continued it consists of the original exception plus some continue information. If it has been continued by several handlers it will contain a lot of continue information in addition to the original exception information. The exception information describes a trace from the point of raise through all the handlers. The TraceId variable that is bound in the try-catch construction gives access information about the entire trace (hence the name).

As mentioned above the program will terminate with en error message, if an exception is raised and no handler can be found. Therefore programs normally setup an outermost default exception handler. mainExe::run setup such a handler in a console program this is the fall-back handler. In a GUI program there is also a default hander in the GUI event loop which will catch exceptions arising from the handling of an event.

All in all, the lifecycle of an exception is as follows:

  • It is raised
  • It is caught and continued
  • It is caught and continued
  • It is caught and handled (or the program terminates with an error message)

Each time the exception is caught the trace so far can be examined. When the exception is raised and each time it is continued extra information can be added to the exception trace. If nothing else handles an exception it will (normally) be handled by the fallback/default handler of the program.

Defining an exception

An exception is a value of the type core::exception

    exception =  exception(string ClassName, string ExceptionName, string Description).

I.e. an exception is a functor term that contains three pieces of information:

The name of the class that defines the exception
Then name of the exception typically the name of a constant in the program
A description of the exception
Example The cannotCreate exception from the example above is declared in the class fileSystem_api like this:
class fileSystem_api
    cannotCreate : exception = exception(class_name(), constant_name(), "Cannot create or open the specified file").

class_name/0-> and constant_name/0-> are built-in predicate that returns the name if the class/constant in which the call occurs. So the line above is equivalent to this:

class fileSystem_api
    cannotCreate : exception = exception("fileSystem_api", "cannotCreate", "Cannot create or open the specified file").

Many/most programmers will never need to define exceptions, because in many/most cases the exceptions to use are already defined. An exception definition is only needed when the exception must be distinguished from other kinds of exceptions, such that exception handlers can deal specially with that kind of exception. Typically exception definitions are only necessary for exceptions that are raised by library software. In most cases programmers will raise the exception internal_error.

Raising an exception

There are many predicates that explicitly raises exceptions, but most of them does it by calling a predicate in exception:

class exception
    raise_exception : (exception Exception, ...) erroneous [programPoint].
    raiseDetailes : (exception Exception, namedValue* ExtraInfo) erroneous [programPoint].
    raise_definiteUser : (exception Exception, string Msg, namedValue* ExtraInfo) erroneous [programPoint].

In alll cases the Exception is the exception to raise and the rest of the arguments provides additional information about the exception. See also programPoint in Language Reference for information about the programPoint attribute.

Example The cannotCreate exception from above is raised by the predicate fileSystem_api::raise_cannotCreate/fileSystem_api::raise_cannotCreate_explicit. The code looks like this:
    raise_cannotCreate_explicit(ProgramPoint, FileName, LastError) :-
        Desc = getLastErrorDescription(LastError),
        Msg = string::format("Cannot create or open '%%%s'\nError = 0x%08x\n%%%s",
            fileSystem_fileName_parameter, LastError, errorDescription_parameter),
        raise_definiteUser_explicit(ProgramPoint, cannotCreate, Msg,
            [namedValue(fileSystem_fileName_parameter, string(FileName)),
            namedValue(fileSystem_path_parameter, string(directory::getCurrentDirectory())),
            namedValue(errorCode_parameter, unsigned(LastError)),
            namedValue(errorDescription_parameter, string(Desc))]).

raise_cannotCreate_explicit is called with the ProgramPoint of the raising predicate, the FileName and the windows error code LastError that the relevant low level Windows API predicate caused.

exception::getLastErrorDescription obtains the description corresponding to LastError from Windows.

exception::raise_definiteUser_explict is then used to raise the cannotCreate exception with the four pieces of extra information. The destinction between errors, user errors and definite user errors are described below.

It is very common to create helper predicates like fileSystem_api::raise_cannotCreate to do the actual raising rather that calling one of the predicates in exception directly from the code that needs to raise the exception. That way it is certain that the extra info for this particular exception is handled in the same way in all cases.

Normally, the helper raise predicate is created by the same programmer that declares the exception. And as mentioned above this is normally only programmers that create library software.

Application programmers will in most cases raise exceptions by calling appropriate raiser predicates, typically the some defined in exception.

Catching and handling exceptions

Exceptions are caught with the try-catch construction:

try Body catch TraceId do Handler end try

If Body terminates with an exception TraceId is bound to the trace id and then Handler is evaluated.

TraceId is used to obtain information about the exception trace. This information can be used for at least two things:

  • Determine which kind of exception that is caught, so that it can be decided if and how to handle it
  • Obtain additional information to write to the user, in a log or use for something else

As explained above it is very common that an exception is continued one or more times after it has been raised, so an exception contains a complete trace of entries (raise, continue, continue, ---). Subsequently, you will need to search the trace to see if a certain exception is among the entries. This is done by calling exception::tryGetDescriptor:

    tryGetDescriptor : (traceId TraceID, exception Exception) -> descriptor Descriptor determ.

The exception trace corresponding to TraceId is searched for an exception of the kind Exception. If there is such an entry in the trace (raised or continued) the corresponding exception descriptor is returned in Descriptor.

The predicate fails if such an exception is not in the exception trace.

The Descriptor contains the extra information about that particular entry in the exception trace:

    descriptor = descriptor(programPointDescriptor ProgramPoint, exception Exception, 
        kind Kind, namedValue* ExtraInfo, gmtTimeValue GMTTime, unsigned ThreadId).


A readable representation of the programPoint where the exception was raised/continued.


The exception in question


The entry kind (raise or continue)


The extra information provided with this entry in the trace


The time this exception trace entry was raised/continued


The exception description of this entry (this information is also present in ExceptionInfo)


The thread id of the thread that raised/continued this entry

Much of this information is mainly interesting if the exception is not handled. The information that is most interesting when handling an exception is:

  • The exception has been determined to be the one we expected
  • The ExtraInfo for this entry is available for use in messages, etc

The predicate exception::tryGetExtraInfo is convenient for obtaining extra information:

    tryGetExtraInfo : (descriptor Descriptor, string Name) -> value Value determ.


Is the description whose extra info we want to get something from.


The name of the extra info parameter we want to obtain.


The value that the mentioned parameter has.
Example Code for catching and handling the fileSystem_api::cannotCreate exception can look like this:
    saveInfo(Filename) :-
         catch TraceId do
              if D = exception::tryGetDescriptor(TraceId, fileSystem_api::cannotCreate) then
                stdio::write("Cannot write to the file: ", Filename),
                if string(Description) = exception::tryGetExtraInfo(D, exception::errorDescription_parameter) then
                    stdio::writef("; %", Description)
                end if,
                exception::continue_unknown(TraceId, "Filename = ", Filename)
            end if
         end try.

The code here don't need to obtain the fileSystem_exception::fileName_parameter, because the file name is already known in the Filename variable.

But we can obtain Window's description of the problem querying for common_exception::errorDescription_parameter

We continue the exception as unknown if it is not a cannotCreate exception. For the continue call we add the filename as additional information. common_exception::continue_unknown will create a string of the extra arguments and add it as an common_exception::errorArguments_parameter. Such information is mainly for use in the default exception handler to be discussed below.

Exception dumps

The class exceptionDump contains predicates for dumping exception traces to stdio, some other outputStream or a string.

An exception dump contains three major pieces of information:

  • A dump of the call stack (with file names and line numbers) from the point where the exception was raised
  • A dump of the exception-trace with all the information from the exception descriptors
  • Information about the operating system that the program ran on

exceptionDump have predicates both for dumping exception traces both from a traceId and from a traceInfo obtained with exception::getTraceInfo (see #Serializing exceptions below).

Dumps for a certain program are in general only useful to the programmers of that program; the users of the program will find dumps cryptic and rather uninteresting. I.e. the purpose of dumps is to give the programmer means for improving the program.

Default handling

A program should handle all exceptions, because if an exception is continued or raised at a point where there is no handler the program will terminate with a rather bad error message. The error message is bad because most exception handling is done in PFC; the language itself knows nothing about exception traces and the like.

To be sure that all exceptions are handled it is normal to set up a default (or fallback) exception handler.

mainExe::run (and mainExe::runCom) which is normally called in the goal setup such a default exception handler: It runs the main::run predicate inside a try-catch construction that will handle any exception.

The handler in mainExe::run (and mainExe::runCom) dumps the entire exception trace to output stream in stdio. And then the program will terminate. The idea is that:

  • Perhaps the user can see something from the dump (which may for example say that access is denied to xxx.txt)
  • Alternatively, the developer of the program may use the dump to improve the program

In addition to the handler in mainExe::run a GUI program also set a default handler in the event loop. This handler is set by calling applicationWindow::setErrorResponder:

    errorResponder = (applicationWindow Source, exception::traceId TraceId).
    setErrorResponder : (errorResponder Responder).

By default the error responder errorPresentationDialog::present is used. The functioning of the <pv>errorPresentationDialog</vp> is closely related to a categorization of exceptions described in the next section.

PFC place exceptions in three major categories based on who is (believed to be) responsible:

Internal errors
An exceptional state which the programmer is responsible to deal with
User exception
An exception which can perhaps be solved by the end user of the program, but which may also call for a programmer solution. User exceptions carries a message for the end user of the program.
Definite user errors
An exception which is definitely one the end user should deal with, because the programmer cannot do anything about it anyway

You may notice that "error" is used to signal that a person is (believed to be) responsible for the problem, where as "exception" also covers situations with looser relation to specific persons (such as a network failure).

Internal errors

Internal errors are caused and/or should be prevented by the programmer of the program.

Example A predicate takes two lists as argument and pair the elements of the lists. So the lists are expected to have the same length. If the lists have different lengths it is appropriate to raise an internal_error, because it is clearly the responsibility of the programmer to ensure that the lists have same length; the end-user of the program can at most influence this indirectly.

User exceptions

User exceptions typically deal with problems related to external resources such as files, network, databases, web servers, etc. Often the user will become wiser by being informed about the problem and often the user may even solve the problem.

Example The read-only file problem discussed above is a typical example of a user exception. It is the user rather than the programmer that can solve the problem with the read-only file.

A user exception is distinguished by having extra information in a field with name common_exception::userMessage_parameter. This extra info should be a message with relevance for an end user of the program. The message can reference other extra info parameters using the format %PARAM. The preferred way to raise user exceptions is by means of the predicate exception::raise_user. Likewise you can continue exceptions with a user message using exception::continue_user.

Example This predicate will raise a user fileSystem_api::cannotCreate exception
class predicates
    raise_cannotCreate : (string Filename) erroneous.
    raise_cannotCreate(Filename) :-
            "It is not possible to create the file %Filename",
            [namedValue("Filename", string(Filename))]).

The use of "%Filename" in the message corresponds to the extra info "Filename".

The predicate exceptionDump::tryGetUserMessage will return a user message from a traceId if possible. The message will consist of all user messages from the entire trace and will have parameters substituted.

Example Given raise_cannotCreate from above and calling test:
    test() :-
         catch TraceId do
            if UserMsg = exceptionDump::tryGetUserMessage(TraceId) then
            end if
         end try.

The following message is written to stdio:

It is not possible to create the file test.xxx

Definite user errors

Definite user errors are exceptions that are solely the responsibility of the user of the program. For example wrong use of the program.

Example A program can write out some information, but only if the user has specified which information to write. So if the user invoke the functionality without having specified which information to write, it is appropriate to raise a definite user error.

A definite user exception is distinguished by adding true as extra info for the parameter exception::definiteUserError_parameter. The preferred way to do this is by using the predicates:

  • exception::raise_definiteUser
  • exception::continue_definiteUser

The use of these predicates is the same as the user of common_exception::raise_user and common_exception::continue_user.

An exception trace is considered a definite user error if one (or more) entries in the trace carries the exception::definiteUserError_parameter. The predicate exception::isDefiniteUserError will succeed for definite user errors.

Serializing exceptions

In some situations the best way to handle an exception is by sending all the information about the exception somewhere else. A server might for example want to send the information to the client program that caused the exception, because then there is a user that can take action.

A traceId only have a meaning in the process that has created it, but the predicate exception::getTraceInfo can create a traceInfo structure (TraceInfo) from the traceId TraceId:

    getTraceInfo : (traceId TraceId) -> traceInfo TraceInfo.

Such a structure is a functor structure that can be serialized/deserialized with toString/toTerm; write/read; nested in a fact database using save/consult; etc.

Packed Exceptions

Some times, e.g., in a client/server application, you catch an exception on the server which you want to handle on the client. In that case you can serialize the exception on the server send it to the client and reraise it as a packed exception.

On the server

catch E do
end try,

On the client

Rtn = remoteCall(...),
if error(TraceInfo) = Rtn then
    exception::raise_packed(TraceInfo, "remoteCall returned an exception")
end if

The predicate raise_packed works like a continue_unknown but continues a serialized exception instead of normal exception. It is meant to be used when the exception stem from another program and thus only is available in serialized form.

The error presentation dialog

The error presentation dialog (in the class errorPresentationDialog) is by default used by the default exception handling in a GUI program. Its behavior is closely related to the classification of exceptions described above, as described by these two rules:

  • If the exception trace carries a user message, this message will be presented to the user.
  • If the exception trace is not a definite user error, there will be information for the programmer

So if the exception is an internal error there will only be information for the programmer; if it is a user exception there will both be information for the user and for the programmer; and if it is a user error there will only be information for the user.

If there is information to the programmer the exception dialog will have a details/less details button that can show/hide the programmer information. It will also have a "report error" button, which by default will copy the information to the clipboard so that the user can easily send it to the programmer.


The dialog is customizable by means of various properties:

    title : string. % := "Error".
    callBackBtnText : string. % := "&Copy".
    dontCallBackBtnText : string. % := "&OK".
    showDetailsBtnText : string. % := "Show &Details".
    hideDetailsBtnText : string. % := "Hide &Details".
    closeApplicationBtnText : string. % := "Close &Application".
    commentTextPromt : string. % := "Please describe what you were doing when the error occured:"
    internalErrorMessage : string. %  := "An internal error has occurred.\nPlease send a bug report to your vendor.".
    feedbackMessage : string. %  := "Please send your feedback.".
    definiteUserErrorIcon : vpiDomains::resid.
    userErrorIcon : vpiDomains::resid.
    internalErrorIcon : vpiDomains::resid.
    reportErrorDelegate : reportErrorDelegate.
    extraInfoWriter : writer.

All texts and labels are controlled by properties.

The extraInfoWriter is a callback that can be set to include extra info for the programmer. This information will both be presented in the details window and reported back to the programmer if the user press the "report error" button (i.e. the button which is by default labeled Copy).

The extraInfoWriter callback predicate must have this type:

    writer = (outputStream Stream).

The dialog will invoke the predicate and then it should simply write extra information to the received stream.

Example The Visual Prolog IDE uses the extraInfoWriter to write version information, information about the open project and information about the last actions carried out in the IDE. This information will help the programmers to analyze the problem.

The action performed by the "report error" button is customizable using the property reportErrorDelegate, which is a callback predicate of this type:

    reportErrorDelegate = (window Parent, string Comment, optional{exception::traceInfo} TraceInfo, string ExtraInfo).
The error presentation dialog which can be used as parent for additional dialogs.
The users comment from the comment box.
If the dialog is invoked on an exception the trace info is here, if it is invoked for feedback this value is none
The extra info written by the extraInfoWriter callback
Example In the Visual Prolog IDE the reportErrorDelegate will send the exception information to a WEB service which will insert the notification in a database. The notifications in the database will then be used to improve the IDE.