Conditions and exceptions

19.1  Exceptions

The goals of the exception mechanism are to help programmers share code which relies on exception handling, and to provide information on violations of specifications of procedures and syntactic forms. This exception mechanism is an extension of SRFI 34 [22], which was primarily designed to meet the first goal. However, it has proven suitable for addressing the second goal of dealing with violations as well. (More on the second goal below in the discussion of the condition system.)

For some violations such the use of unsupported NaNs or infinities, as well as other applications, an exception handler may be able to repair the cause of the exception, for example by substituting a suitable object for the NaN or infinity. Therefore, the exception mechanism extends SRFI 34 by continuable exceptions, and specifies the continuation of an exception handler

19.2  Conditions

Conditions are values that communicate information about exceptional situations between parts of a program. Code that detects an exception may be in a different part of the program than the code that handles it. In fact, the former may have been written independently from the latter. Consequently, to facilitate effective handling of exceptions, conditions should communicate as much information as possible as accurately as possible, and still allow effective handling by code that did not precisely anticipate the nature of the exception that has occurred.

The (rnrs conditions (6)) library provides two mechanisms to enable this kind of communication:

As an example, a networking error that occurs during a file operation on a remote drive fits two descriptions: “networking error” and “file-system error”. An exception handler might only look for one of the two. Compound conditions are a simple solution to this problem. Moreover, compound conditions also make providing auxiliary information as part of the condition object, such as an error message, easier.

The standard condition hierarchy makes an important distinction between errors and violations: An error is an exceptional situation in the environment, which the program cannot avoid or prevent. For example, I/O errors are represented by condition types that are subtypes of &error. Violations, on the other hand, are exceptional situations that the program could have avoided. Violations are typically programming mistakes. The distinction between the two is not always clear, and it may be possible but inordinately difficult or expensive to detect certain violations. The use of eval also blurs the distinction. Nevertheless, many cases do allow distinguishing between errors and violations. Consequently, exception handlers that handle errors are common, whereas programmers should introduce exception handlers that handle violations with great care.