Previous Chapter | Next Chapter | Up | Next Section | Contents

Exception Handling with the try Tag


Exceptions are unexpected errors Zope encounters during the rendering of a DTML statement. Once an exception is detected, the normal execution of the DTML stops. Consider the following example:

Cost per unit: $<!--#var expr="_.float(total_cost/total_units)"-->

This statement functions normally if total_units is not zero. However, in the event that total_units is zero, a ZeroDivisionError exception is raised indicating an illegal operation. Thus, rather than rendering the DTML, an error message will be returned.

DTML provides the try tag to catch and handle these problematic exceptions within a block of DTML code. This allows you to anticipate and handle errors yourself, rather than getting a Zope error message whenever an exception occurs. As an exception handler, the try tag has two functions. First, if an exception is raised, the try tag gains control of execution and handles the exception appropriately, and thus avoids returning a Zope error message. Second, the try tag allows the rendering of any subsequent DMTL to resume.

Within the try tag are one or more except tags that identify and handle different exceptions. When an exception is raised, each except tag is checked in turn to see if it matches the exception's type. The first except tag to match handles the exception. If no exceptions are given in an except tag, then the except tag will match all exceptions.

Implementing the try tag in the example above would resemble:

<!--#try-->

Cost per unit: $<!--#var expr="_.float(total_cost/total_units")-->

<!--#except ZeroDivisionError-->

Cost per unit: N/A

<!--#/try-->

If a ZeroDivisionError is raised, control goes to the except tag, and "Cost per unit: N/A" is rendered. Once the statements of the except tag finish, execution of DTML continues past the try block.

DTML's except tags work with Python's class-based exceptions. In addition to matching exceptions by name, the except tag will match any subclass of the named exception. For example, if ArithmaticError is named in an except tag, the tag can handle all ArithmaticError subclasses including, ZeroDivisionError.

Inside the body of an except tag you can access information about the handled exception through several special variables. These variables are: error_type, which represents the type of the handled exception, error_value , which represents the value of the handled exception, and error_tb , which represents the traceback of the handled exception.

Previous Chapter | Next Chapter | Up | Next Section | Contents