[Home] [Credit Search] [Category Browser] [Staff Roll Call] | The LINUX.COM Article Archive |
Originally Published: Wednesday, 30 August 2000 | Author: Jason Tackaberry |
Published to: develop_articles_tutorials/Development Tutorials | Page: 5/6 - [Printable] |
Programming with Python - Part 1: Baby Steps
This tutorial is the first in a series that will introduce you to Python, a dynamic, object-oriented language that is rapidly gaining popularity. Since I myself have garnered a modest Perl background before learning Python, I will target this tutorial at the Perl programmer. However, anyone with a little programming experience should find this text useful.
|
<< Page 5 of 6 >> | |
An Exception to the RuleError handling in Python is done using exceptions. When a statement or expression is executed, it may need to signal some sort of error message. It does this by raising an exception. For example, suppose we try to open a file that doesn't exist:
Executing this code will output:
Obviously it's not acceptable to have your program bail out every time it encounters an error as simple as a non-existent file. In Python, you first try the code, and can specify a block of code to be executed upon one, many, or all exceptions:
Now, if the open fails, it will print "Open failed!" and move on. It's entirely possible (and likely) that an expression can generate more than one exception. So in our example, we may just want to handle IOError exceptions. We can do this by specifying the exception type after the except keyword:
But there are different kinds of IOErrors; the file may not exist, or perhaps it is not readable to the user trying to open it. Note in the exception error generated above, the No such file or directory error number was 2. Exceptions may have arguments associated with them, and we can fetch these arguments like so:
The IOError is one of many built-in exceptions. You can create your own custom exceptions, as well. In fact, the exception may be identified by either strings or instance objects. (You can identify an exception by a class object, but Python will just use that class object to create an instance before raising the exception.) A simple example of raising an exception identified by a string is:
| |
<< Page 5 of 6 >> |