Exercises, examples and other material relating to training module Y109. This topic is presented on public courses
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.
|Articles and tips on this subject||updated|
|4161||Python varables - checking existance, and call by name or by value?|
A couple of good questions from a recent delegate...
Q. How do I check for the existance of a variable in Python?
A. Reference it and see if an exception is thrown. Here's an example in which I create a variable only if my program is run with command line parameters:
|4029||Exception, Lambda, Generator, Slice, Dict - examples in one Python program|
A new example from last week's Python course, showing exception, lambda, generator and list slices in a practical programming example. The task we took was to go through a file of railway stations and ticket sales figures, and report on the most and least used 20 in the UK. The programs's [here].
|3930||Reporting the full stack trace when you catch a Python exception|
Python exceptions are a safety net which let you catch data or program problems or other unexpected issues without having to explicity code each and every potential problem or problem group - a wonderful fail safe mechanism.
If you fail to write your Python code with try and except blocks, it will use ...
|3913||How many times ... has this loco headed west through Tenby? - Python exceptions|
If you have a stock of 117 locomotives on your railway, and each is on the front of a train through Tenby as it heads for Pembroke just 12 times a year (it's a Summer Saturday Special working!), will - in the course of their 30 year life - every locomotive have worked that train? Will the reason that ...
|3664||Error checking in a Python program - making your program robust via exceptions|
Error checking of inputs, in some way, is vital. You may use conditionals such as if, you may precheck data before it reaches your program, or you may do both. But can you be sure you'll meet every eventuality? It's a difficult game forecasting everything that might go wrong. By using excpetions, ...
|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, ...
|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) ...
|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 ...
|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 ...
|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 ...
|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.
|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 ...
|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 ...
|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 ...
|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
taxrate /= 100.
|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 ...
|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 ...
|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 ...
|attempt|| full traceback log from exceptions|
|bug.py|| Program with a bug!|
|dbnover|| Events spread over a number of units|
|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|
|kx|| Answer to exercise|
|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|
|railx|| Busiest and quietest stations|
|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|
|topstats|| Exception, Lambda, dict|
|trapper.py|| Use of try and except|
|ui|| Read an integer - validated|
|wholehog.py|| static variable - initialise via exception|
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
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.
If you are looking for a complete course and not just a information on a single subject, visit our Listing and schedule
Well House Consultants specialise in training courses in
. We run
throughout the UK (and beyond for longer courses), and
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.