8) b. try, except statements

Now that you know how to read error messages you need to learn how to deal with the exceptions gracefully.

Think of it like this. After you’ve run your program a couple of times you might encounter exceptions (errors).

When that happens you will know exactly which line can cause a failure and what the failure can be (by seeing the traceback). For example, when you’re dividing two numbers by accepting values from the user, then your program might throw a ZeroDivisionError.

Sometimes you might be able to guess in advance that an exception might occur on a particular line of code. For example, when you’re opening a file, what if the file is in use by another application and locked?

In these cases, you would want your program to handle the error gracefully and exit by giving the user a meaningful message.

Take a look at this example. Try running the following code and see what happens:

1
2
Output:
KeyError: Garry on line 8


As you can see, this program terminates with a KeyError exception.


But we don’t want our programs to terminate this way with an exception. Instead, we can use the try, except statements to take care of exceptions that might be thrown. Take a look at the following program:

1
2
3
4
5
6
7
Alice has a grade 86  and gpa 3.44 .


No record of a student with the name Garry


David 's mark is corrupted. Must be a numeric value.



You can also catch all exceptions by using a generic catch-all exception. The following program illustrates how you can catch any exception and print the error.

1
2
3
4
5
6
Output:
Exception occured. There are only 8 planets.


Error details:
IndexError: list index out of range on line 5