Home arrow Python arrow Page 3 - Python 101 (part 8): An Exceptionally Clever Snake

Trying Harder - Python

In this concluding article of the Python 101 series, find out howto use Python's exception-handling routines to trap and resolve programerrors, learn to generate and use custom error messages, and get acquainteda bunch of useful (and free!) Python resources online.

TABLE OF CONTENTS:
  1. Python 101 (part 8): An Exceptionally Clever Snake
  2. Anatomy Of An Exception
  3. Trying Harder
  4. Different Strokes
  5. Passing The Buck
  6. Bad Boys
  7. Raising The Bar
  8. Strong Pythons (And The Exceptions That Love Them)
  9. The End Of The Affair
By: Vikram Vaswani, (c) Melonfire
Rating: starstarstarstarstar / 8
August 23, 2001

print this article
SEARCH DEV SHED

TOOLS YOU CAN USE

advertisement
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:

try: execute this block except err1: execute this block if exception "err1" is generated except err2: execute this block if exception "err2" is generated

... and so on ...

else: execute this block
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.

#!/usr/bin/python

alpha = input("Gimme a number: ") beta = input("Gimme another number: ") gamma = alpha / beta print alpha, "divided by", beta, "is", gamma
Now look what happens when I run this with different values.

Gimme a number: 10 Gimme another number: 2 10 divided by 2 is 5

Gimme a number: 10 Gimme another number: 0 Traceback (innermost last): File "div.py", line 6, in ? gamma = alpha / beta ZeroDivisionError: integer division or modulo

Gimme a number: 67347328 Gimme another number: 943282646373739 Traceback (innermost last): File "div.py", line 4, in ? beta = input("Gimme another number: ") OverflowError: integer literal too large

Let's now add a couple of exception handlers to this code, so that it knowshow to gracefully handle errors like the ones above:

#!/usr/bin/python

try: alpha = input("Gimme a number: ") beta = input("Gimme another number: ") gamma = alpha / beta print alpha, "divided by", beta, "is", gamma except ZeroDivisionError: print "Cannot divide by zero!" except OverflowError: print "Number too large!" else: print "No errors encountered!"

print "-- All done --"
And now let's try the different test cases above again:

Gimme a number: 10 Gimme another number: 2 10 divided by 2 is 5 No errors encountered! -- All done --

Gimme a number: 10 Gimme another number: 0 Cannot divide by zero! -- All done --

Gimme a number: 823748237 Gimme another number: 234378264732647326476327 Number too large! -- All done --

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.

 
 
>>> More Python Articles          >>> More By Vikram Vaswani, (c) Melonfire
 

blog comments powered by Disqus
escort Bursa Bursa escort Antalya eskort
   

PYTHON ARTICLES

- Python Big Data Company Gets DARPA Funding
- Python 32 Now Available
- Final Alpha for Python 3.2 is Released
- Python 3.1: String Formatting
- Python 3.1: Strings and Quotes
- Python 3.1: Programming Basics and Strings
- Tuples and Other Python Object Types
- The Dictionary Python Object Type
- String and List Python Object Types
- Introducing Python Object Types
- Mobile Programming using PyS60: Advanced UI ...
- Nested Functions in Python
- Python Parameters, Functions and Arguments
- Python Statements and Functions
- Statements and Iterators in Python

Developer Shed Affiliates

 


Dev Shed Tutorial Topics: