Python/Try Statement

< Python

Objective

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

Lesson

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 occur 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 try and except statements. A minimal example is given below.

>>> try:
...     print(spam)
... except:
...     print("spam isn't defined!")
...
spam isn't defined!


If any code within the try statement causes an error, execution of the code will stop and jump to the except statement. Here it will execute the code and if, for any reason, there's an error within the except statement, you'll get the message During handling of the above exception, another exception occurred. You should be careful not to put any code that could cause an error within the except 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 NameError 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 NameError? To do this, we need to have the said error follow after the except statement as show in the example below.

>>> try:
...     print(spam)
... except NameError:
...     print("spam isn't defined!")
... except:
...     print("An unknown error has occurred!")
...
spam isn't defined!


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

Exceptions

The Else Statement

The else statement, functions just like does with the while and for statements. It executes if the try statement finishes without any errors or premature endings. This statement must come after the group of except statements like the example below demonstrates.

>>> try:
...     spam = 7
...     print("I have %d cans of spam!" % spam)
... except:
...     print("Some error has occurred!")
... else:
...     print("Everything went smoothly!")
...
I have 7 cans of spam!
Everything went smoothly!

The Finally Statement

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

>>> try:
...     print("pop")
... except:
...     print("An error has occurred!")
... else:
...     print("Everything went smoothly!")
... finally:
...     print("Finishing up now...")
...
pop
Everything went smoothly!
Finishing up now...
>>> try:
...     print("soda")
... except:
...     print("An error has occurred!")
... finally:
...     print("Cleaning up any mess...")
...
soda
Cleaning up any mess...

Assignments

Completion status: Almost complete, but you can help make it more thorough.

  1. Python Software Foundation. "Exception hierarchy" (HTML). Built-in Exceptions. Retrieved 2015-05-05.
This article is issued from Wikiversity - version of the Wednesday, May 06, 2015. The text is available under the Creative Commons Attribution/Share Alike but additional terms may apply for the media files.