Python offers two flavours of exception handler - the first is the"try-except" construct you just saw, while the second is the "try-finally"construct. The "try-except" construct - actually the "try-except-else" construct -allows developers to trap different types of errors and execute appropriateexception-handling code depending on the exception type. It's a lot likethe "if-elif-else" conditional construct, allowing for the execution ofdifferent code blocks depending on the type of error generated. The structure of a "try-except-else" block looks like this: When Python encounters code wrapped within a "try-except-else" block, itfirst attempts to execute the code within the "try" block. If this code isprocessed without any exceptions being generated, Python checks to see ifthe optional "else" block is present. If it is, the code within it isexecuted. If an exception is encountered while running the code within the "try"block, Python stops execution of the "try" block at that point and beginschecking each "except" block to see if there is a handler for theexception. If a handler is found, the code within the appropriate "except"block is executed; if not, control either moves to the parent "try" block,if one exists, or to the default handler, which terminates the program anddisplays a stack trace. Once the "try" block has been executed and assuming that the program hasnot been terminated, the lines following the "try" block are executed. Let's illustrate this with a simple Python program, which accepts twonumbers and attempts to divide them by each other. Now look what happens when I run this with different values. Let's now add a couple of exception handlers to this code, so that it knowshow to gracefully handle errors like the ones above: And now let's try the different test cases above again: Depending on the type of error encountered, the appropriate exceptionhandler is triggered and an error message displayed. The optional "else"block is executed at the end of the script *only* if no exceptions areencountered. Once an exception has been caught and resolved, the remainder of the "try"block is ignored and Python executes the lines following the entire"try-except-else" block.
blog comments powered by Disqus |