Try Statement - Python (2016)

Python (2016)

CHAPTER 14: Try Statement

In the perfect programming world, nothing would go wrong. Unfortunately, even the best programmers make mistakes—that’s why debugging and troubleshooting has become a core part of the development process. Aside from manual mistakes, computers may go wonky—crashing, resetting, and shorting out in perfect manifestation of Murphy’s Law. In the even something goes south, the computer will have to act in a flash and recognize that something is going on. At this stage, the computer should also stop and try to fix the problem when it could. Any well-coded software should have at least the basic safeguards in place for such events.

In programming, an error is produced when the computer has detected something is off. Take, for example, when you are burning a CD. When you pull out the CD without waiting for it to complete, then the CD will be unavailable to the software you are using. If the software is not equipped to handle this kind of behavior then the computer will throw an “undefined” message. Or, the program could just hang as it tries to burn something onto a non-existent media. These types of behavior aren’t too useful for the user, so one should create a way to handle them. Fortunately, in Python, the programmer can write codes that handle exceptions and errors. This is in contrast to many other programming languages.

Errors—Python vs C

As you might have noticed when you mistype things in the Python interpreter, the language’s errors are very “loud”. This means that when something is not right, Python will ensure that you know about it in the surest way. Others may balk at having every single mistype scrutinized by an unforgiving system, but as you go on this actually becomes a necessity.

Let’s take a step back and look at one of Python’s forebears, the C language. It did not have the built-in error handling that Python now has. Sometimes, the errors just slip by unnoticed by anyone. This is actually good, since that means the error is “tolerable”. However, there are some times when the error causes the computer to crash outright—these are dangerous in many aspects. Because the language does not allow for error handling, the programmer will have to create their own. This still does not make it easy to catch all the errors in their tracks.

This is why Python was built with such a sharp eye for errors. Once the language fulfills its goal of notifying you, you have the buck and the control of what else to do from thereon. If you do not make any specific call for Python, a default message is then displayed which is follows by the program’s termination.

Loud Errors

Now that we understand the Python errors in a better light, it is clear that handling these errors become just as important as displaying them. Let’s say that you create a large program, which crashes each time you use it. Finding and fixing the issue will become very important. Python’s loud errors will let you know not just what the error is, but what caused it too. This allows for faster development due to the faster fixing of errors.

The Try and Except Statement

As far as error-handling goes, we can use the try and except statements. Their usage is shown in the following (minimal) example:

>>>try:

... Print(eggs)

... Except:

... Print(“eggs has not been defined”)

...

Eggs has not been defined

As you noticed, id a piece of code that has the try statement causes an error, then the code execution will stop. From there, it will jump to the except statement. The code in the except will then be executed, and a different error will appear when the except statement causes another conflict:

During handling of the above exception, another exception occured.

This is why it is important to mind the except, since you would not want to put another error-causing code there.

You might also have found from prior experience, that the third line of the error message will be the one that specified what kind of error happened. In the earlier example, a NameError has occurred. This is the type of issue that erupts when the name of a variable cannot be found. This is commonly because the variable does not exist in the first place. Since the errors can be quite specific, there has to be a set of different exception names—and there really are! The language has at least 20 well-defined and built-in exceptions to address each kind of known problem.

So what will happen if the programmer tries to catch the NameError (or any other specific error for that matter)? In order to do this, one would have the specific error after the except statement as demonstrated in the following example:

>>>try:

... Print(jam)

... Except NameError:

... Print(“Jam is not defined”)

... Except:

... Print(“An unidentified error appeared”)

...

Jam is not defined

As we can see, the except statement acts by itself as the default error handler. It can handle any error that has not been captured by another except statement. This will mean that you can use a multitude of except statements used to catch errors.

The Else Statement

Again, we can use the else statement in this regard. Just like how it works with the for and while statements, it will execute when the try statement terminates without any premature endings or errors. The statement should also come after the set of except statements, such as demonstrated in the example below:

>>>try:

... Eggs=6

... Print(“I have %d baskets of eggs” %eggs)

... Except:

... Print(“An error has occurred”)

... Else:

... Print(“Everything is fine”)

...

I have 6 baskets of eggs

Everything is fine

The Finally Statement

This statement is technically similar to the previously-tackled else statement, except that the finally will always execute when the try statement has failed or when it has prematurely failed. This statement should go after the else statement, such as is shown below:

>>>try:

... Print(“spam”)

... Except:

... Print(“There is an error”)

... Else:

... Print(“Everything is fine”)

... Finally:

... Print(“Wrapping up”)

...

Spam

Everything is fine

Wrapping up

>>>try:

... Print(“juice”)

... Except:

... Print(“There is an error”)

... Finally:

... Print(“Wrapping up”)

...

Juice

Wrapping up