You can also write specific exception handlers for different types of exceptions, by noting the exception type within the Here's the output: Of course, this handler will now only restrict its activities to KeyError exceptions. All other errors will be routed via the default Zope error handler. You can trap more than one exception, and handle each one in a different way, by using multiple <dtml-except> statements within a single <dtml-try> block. If an exception is encountered while running the code within the <dtml-try> block, Zope stops execution of the <dtml-try> block at that point and begins checking each <dtml-except> block to see if there is a handler for the exception. If a handler is found, the code within the appropriate <dtml-except> block is executed; if not, control either moves to the parent <dtml-try> block, if one exists, or to the default handler. Once the <dtml-try> block has been executed and assuming that the program has not been terminated, the lines following the <dtml-try> block are executed. In case you're wondering, the <dtml-else> branch in the block above is executed only if no exceptions are raised. It's optional, though, so only include it if you need to. Take a look at the next example, which demonstrates how this works: Save this code in a DTML Document named "ExceptionallyYours", and test it by passing it values for the variables "alpha" and "beta" on the URL string, via the GET method (you can also use a form and submit values for these variables via POST). For example, if you access the URL you'll see But look what happens when you try Since no values have been passed for the variables, Zope barfs with a KeyError, which is caught by the exception handler, and the following message is displayed: What about if you pass an illegal value, like a very large integer? Try the following URL, and then see what Zope says: Finally, try attempting division by zero, and watch as Zope generates a ZeroDivisionError, and an appropriate message. If you'd like to save yourself some keystrokes, you also have the option of handling multiple exceptions within a single <dtml-except> block, by specifying a list of exception types separated by spaces. Consider the following rewrite of the previous example, which uses the same exception handler for both ZeroDivisionError and ValueError exceptions:
blog comments powered by Disqus |