Exercises, examples and other material relating to training module Y109. This topic is presented on public courses
Learning to program in Python,
Python Programming
There's a limit to how many checks you can build into programs, and some things (such as a connection being lost) that you can't check for at all. Exceptions allow you to try to run a block of code, and if it fails you jump to a block that catches the exception so that you can.
Related technical and longer articles
errors v exceptions
| Articles and tips on this subject | updated |
| 3441 | Pressing ^C in a Python program. Also Progress Bar. If you want to stop a user interrupt via ^C aborting your program, you can catch a KeyboardInterrupt in Python. There's an example [here] which I wrote earlier today. It also shows how important it might be to use two try/except blocks rather than one - I've specified two inputs in the same block and, ... | 2011-09-16 |
| 3433 | Exceptions - a fail-safe way of trapping things that may go wrong As part of a previous post, I was looking at the "Internal Server Errors" logged on our web server over the past 3 months ... and I found one coming from a Python / CGI demonstration which I wrote and uploaded for a delegate a couple of months back.
Internal server error 500 (by default on Apache httpd) ... | 2011-09-11 |
| 3177 | Insurance against any errors - Volcanoes and Python Have you heard of people who have taken out insurance, only do discover that they're not covered for some eventuality - "but the list of circumstances doesn't include your flight being canceled because the plane couldn't fly through volcanic ash" is a story that many people heard, with an irony that ... | 2011-02-20 |
| 2998 | Using an exception to initialise a static variable in a Python function / method Exceptions are sometimes "sold" as a way of trapping errors - but they're more than that - they're an excellent way of trapping conditions where there isn't a valid result.
"How many people live in this house" you may ask of a function / method call, and the answer may come back as "2" or "5" ... or ... | 2010-10-20 |
| 2994 | Python - some common questions answered in code examples Some tips and new examples from last week ... Python in Plymouth!
• How do I put comments in a Python regular expression to make it more readable: [source]
• How do I use a python dictionary as a table of counters - in our example, counting the number of people in our team who have each of ... | 2010-10-10 |
| 2622 | Handling unusual and error conditions - exceptions "I can't answer that question in the way you expect" ... that's something that may be said to you occasionally - you ask someone what suit a playing card is that they're holding and they cannot tell you because it is a joker, or you ask what number is written on a piece of paper when the paper is blank.
The ... | 2010-02-03 |
| 2408 | Robust user input (exception handling) example in Python One of the questions in the "exceptions" section of the Python Course asks my delegates to "Graham Proof" a piece of code:
first = int(input("First number: "))
second = int(input("Second number: "))
print "Sum is "+str(first+second)
The idea is that I come round the room and put really awkward inputs ... | 2009-09-20 |
| 2368 | Python - fresh examples of all the fundamentals Some more new examples in Python - from this week's course.
From my Introduction to Python / simple example to show the power of the language, I present my example that parsed a big data (log) file and counter and sorted by number of accesses the hits from various remote hosts. A long report, ending ... | 2009-08-23 (longer) |
| 2281 | Python - using exceptions to set a fallback In Python, you should use exceptions to catch error conditions such as files that you're unable to open, broken network connections, and user inputs which give a problem - it's all very well putting traditional checks in your code, but you'll be well advised to use try and catch as well for additional ... | 2009-07-12 |
| 2018 | UnboundLocalError - Python Message What does THIS mean?
UnboundLocalError: local variable 'taxrate' referenced before assignment
It means that you have tried to modify the value of a variable - perhaps in a function - before you have given it an initial value:
taxrate = 15
def getnet(gross):
taxrate /= 100.
net ... | 2009-01-31 |
| 1236 | Trying things in Python Are you used to writing long sections of code to validate user input? Perhaps you are, or perhaps you have shortened such code over the years using Regular Expressions where you can specify a pattern to be matched. One regular expression can replace 30 lines of other code.
But in Python, Java and ... | 2007-06-18 |
| 1042 | Nested exceptions in Python Yes, you can nest exceptions in Python - here's an example from yesterday's course.
I'm reading in lines from a data file and counting the numbe of occurrences of a particular series of events in a dictionary of dictionaries.
An exception is thrown if a counter doesn't already exist ... we'll catch ... | 2007-01-18 |
| 381 | Exceptions in Python Rather than having to check ahead of time for every possible error, Python provides an exception handling capability too. Simply try to perform you action, and define what's to be done in an except block if the action you want can't be completed.
Here's an example in which we (try to) read an integer ... | 2006-06-05 |
Examples from our training material
| bug.py | Program with a bug! |
| deltemp.py | Use of pass to provide an empty block |
| ewhy.py | Using excpetion for fail-safe error handling |
| grabot.py | Read from a URL resource with error trapping |
| gwrong.py | Using excpetions to allow *some* user errors |
| insist.py | try and except within a loop |
| maffs.py | static variable in Python |
| ouch | try, except, finally example |
| oy | Raising Exceptions yourself |
| prog | Status line. Also trapping ^C |
| pushit.py | Handling multiple exceptions types |
| ranger.py | passing exceptions back to calling code |
| runtime.py | Example of a runtime error |
| sometimes.py | Example of a piece of code that sometimes crashes |
| stopc | trapping ^C in Python |
| syntax.py | Example of a syntax error |
| trapper.py | Use of try and except |
| ui | Read an integer - validated |
| wholehog.py | static variable - initialise via exception |
Pictures
Python practical on a Public training course in Melksham
Background information
Some modules are
available for download as a sample of our material or under an
Open Training Notes License for free download from
http://www.training-notes.co.uk.
Topics covered in this module
What is an exception?.
Using try and except.
Types of exceptions.
Running mandatory cleanup code.
Raising an exception.
Practical examples - exceptions in use.
Simple application - generate a list of prime numbers.
Code testing and optimisation.
Complete learning
If you are looking for a complete course and not just a information on a single subject, visit our
Listing and schedule page.
Well House Consultants specialise in training courses in
Python,
Perl,
PHP, and
MySQL. We run
Private Courses throughout the UK (and beyond for longer courses), and
Public Courses at our training centre in Melksham, Wiltshire, England.
It's surprisingly cost effective to come on our public courses -
even if
you live in a different
country or continent to us.
We have a technical library of over 700 books on the subjects on which we teach.
These books are available for reference at our training centre. Also
available is the Opentalk
Forum for discussion of technical questions.