Python Concepts/Try Statement

Objective

 * Learn about errors and exceptions.
 * Learn how error handling differs from C.
 * Understand why errors and exceptions never pass silently.
 * Learn about the,  ,  , and   statements.
 * Read a list of built-in exceptions.

Page Index

 * Try Statement:Lesson
 * Try Statement:Examples
 * Try Statement:Assignments
 * Try Statement:References

Errors and Exceptions
In a perfect world, nothing goes wrong. Unfortunately, we don't live in a perfect world, so bad things are bound to happen. Computers can crash, monitors can short, and hard drives can corrupt. In the event that something goes wrong, purposely or not, the computer needs to be able to understand that something is going wrong and stop/fix the problem. Software also needs to be able to handle these problems, too.

Errors happen when something doesn't go right. For example, pulling a CD out of a computer while burning something on it will result in the CD not being completely finished (corrupted) and it will also make the CD unavailable to the software using it (the CD burning program). If the program can't handle this problem it might display undefined behavior, like trying to continue burning to a nonexistent CD or the program could just hang. That's not very helpful to the user, so it's important to take care of these errors. Luckily, Python is able to handle errors and exceptions, unlike other programming languages.

Python Errors vs. C Errors
As we've seen so far in this course, errors are very loud in Python. If something doesn't follow the rules or doesn't go right, Python will make sure you hear about it. Having every little mistake scrutinized without mercy might sound bad at first, but it actually becomes a vital necessity when you learn why. Early programming languages, like C, didn't come with built-in error handling. Sometimes errors went by unnoticed. Other times they caused the computer to crash. It was up to the programmer to create their own error handling support and even then it was still hard to catch errors in their tracks. Python's ultimate error handling goal is to let you know that an error has occurred. Having fulfilled its goal, what happens next is all up to you. If you don't specify anything to happen, then a default error message is displayed and the program is ended.

Loud Errors
Now that we have a bigger picture on errors, it becomes clear that handling errors is important. Imagine creating a large program. The said program crashes when you use it. It then becomes really important on finding and fixing the problem. Python lets you know where the error occurred and what caused the error. This simplifies the error fixing process and it allows for rapid development with the knowledge that errors don't go unnoticed. This is one of the many situations where error handling comes in handy.

The Try and Except Statements
Python allows for errors and exceptions to be handled by the program. To do so, you'll need to use both the  and   statements. A minimal example is given below.

If any code within the  statement causes an error, execution of the code will stop and jump to the   statement. Here it will execute the code and if, for any reason, there's an error within the  statement, you'll get the message. You should be careful not to put any code that could cause an error within the  statement.

Now, you might have noticed that error messages will identify what kind of error happened on the third line. In the case of the earlier example, a  occurred. This kind of error happens when a variable's name can't be found, usually because it doesn't exist. Since errors can be very specific, there needs to be an array of different exception names and there are. Python has at least 20 different built-in exceptions so each problem can be addressed.

Now, what happens if we want to catch a specific error like ? To do this, we need to have the said error follow after the  statement as shown in the example below.

We can see that the  statement by itself acts as a default error handler. It will handle any errors not caught by another. This means we can have ten different  statements working to catch errors.

Exceptions
Needs some work...

BaseException +-- SystemExit +-- KeyboardInterrupt +-- GeneratorExit +-- Exception +-- StopIteration +-- ArithmeticError |   +-- FloatingPointError |   +-- OverflowError |   +-- ZeroDivisionError +-- AssertionError +-- AttributeError +-- BufferError +-- EOFError +-- ImportError +-- LookupError |   +-- IndexError |   +-- KeyError +-- MemoryError +-- NameError |   +-- UnboundLocalError +-- OSError |   +-- BlockingIOError |   +-- ChildProcessError |   +-- ConnectionError |   |    +-- BrokenPipeError |   |    +-- ConnectionAbortedError |   |    +-- ConnectionRefusedError |   |    +-- ConnectionResetError |   +-- FileExistsError |   +-- FileNotFoundError |   +-- InterruptedError |   +-- IsADirectoryError |   +-- NotADirectoryError |   +-- PermissionError |   +-- ProcessLookupError |   +-- TimeoutError +-- ReferenceError +-- RuntimeError |   +-- NotImplementedError +-- SyntaxError |   +-- IndentationError |        +-- TabError +-- SystemError +-- TypeError +-- ValueError |   +-- UnicodeError |        +-- UnicodeDecodeError |        +-- UnicodeEncodeError |        +-- UnicodeTranslateError +-- Warning +-- DeprecationWarning +-- PendingDeprecationWarning +-- RuntimeWarning +-- SyntaxWarning +-- UserWarning +-- FutureWarning +-- ImportWarning +-- UnicodeWarning +-- BytesWarning +-- ResourceWarning

The Else Statement
The  statement functions just like it does with the   and   statements. It executes if the  statement finishes without any errors or premature endings. This statement must come after the group of  statements like the example below demonstrates.

The Finally Statement
The  statement is similar to the   statement, except it will always execute after the   statement, regardless if it fails or ends prematurely. The  statement must go after the   statement. The example below demonstrates.

Examples
Python has powerful error detection capabilities. If it's possible to produce an error (and it usually is), Python is ready to pounce on it and broadcast to the world if an error has occurred. It's the responsibility of the programmer to anticipate and handle errors so that, despite errors, the job completes successfully or terminates gracefully. We software engineers should be grateful for Python's error detection power; we can spend less time chasing errors and more time writing good code.

We've seen some errors already: Let's review some of these errors and a few more and create situations in which they are likely to occur.

Python's  statement is a means which we can use to handle errors gracefully. If the error is handled properly, execution of the code does not produce error status and there is no output to stderr.

The above exits with status = 0 and there is no output to stderr.

File "t3.py", line 9 exit (0) ^ IndentationError: expected an indented block

Traceback (most recent call last): File "t3.py", line 5, in    a =[1,2,3]; a[4] IndexError: list index out of range

During handling of the above exception, another exception occurred:

Traceback (most recent call last): File "t3.py", line 6, in    except Indexerror : NameError: name 'Indexerror' is not defined The example above stresses that the code processing errors should not introduce another error.

Correct the spelling mistake and try again:

The following code tests a selection of different errors, including errors raised by the code and also an error  defined by the user.

condition = 1. ZeroDivisionError detected.

condition = 2. IndexError detected.

condition = 3. NameError detected.

condition = 4. TypeError detected.

condition = 5. KeyError detected.

condition = 6. NameError detected. # I cannot explain this.

condition = 7. ZeroDivisionError detected.

condition = 8. IndexError detected.

condition = 9. NameError detected.

condition = 10. TypeError detected.

condition = 11. KeyError detected.

condition = 12. OverflowError detected.

condition = 13. Arrived at label.

condition = 14. Unknown error detected: (, IndentationError, ) ["", 'None', '']

condition = 15. Unknown error detected: (, UnicodeError, ) ["", '', '']

condition = 16. Smooth sailing.

Testing your code
Thorough testing of your code requires that you deliberately subject your code to all sorts of error conditions and then check that the code handles all errors gracefully.

If an error condition causes your program to halt (and it usually does), restarting the application to continue testing for other error conditions can be very time-consuming.

Python's  statements are an excellent way to capture errors, and many slow restarts are avoided because SystemExit is a condition that can be trapped and processed like so many others.

This section describes a simple example full of errors that are all handled very simply and gracefully with Python's  statements.

Password checking
Suppose that your piece of code checks a password for "strength." The usual requirements are that the password should be a certain length, that it should contain or should not contain certain characters and so on.

Preparation
The following piece of code includes extra tests to reject substrings such as "hijk", "ponm", "qwerty" or "9876". Hopefully the error messages in the code are self explanatory.

Sample passwords
In the next piece of code there is a string containing 20 sample passwords, all of which except one fail the test. The passwords in the string are converted to commands within list "instructions".

Testing each password
The next piece of code tests each password.

Assignments



 * Previous Lesson: For Statement
 * This Lesson: Try Statement
 * Next Lesson: With Statement
 * Course Home Page