Python Intermediate: Objects, Errors and Files
Errors and Exceptions
In this lesson you will
- Read an error message and traceback
- Handle exceptions with try, except, else and finally
- Raise errors and create a custom exception
Introduction
Programs meet problems: a file is missing, a user types letters where a number belongs, a network call fails. In Python these problems are exceptions. If you ignore an exception, your program stops with an error message. If you handle it, your program can recover and carry on.
Reading a traceback
When an exception is not handled, Python prints a traceback: the path the program took to the problem. Read it from the bottom up.
The last line says what went wrong (ZeroDivisionError: division by zero). The lines above show where: which line, and which function called which. Learn the most common types:
ValueError: the right type, but a bad value, likeint("abc").TypeError: the wrong type, such as"a" + 1.KeyError: a missing dictionary key.IndexError: a list index out of range.NameError: using a name that does not exist.ZeroDivisionError,FileNotFoundError, and many more.
Quick quiz
In a traceback, which line usually tells you the actual problem?
try and except
Put risky code in try. If an exception happens, Python jumps to except.
Catch specific exception types. A bare except: hides every kind of problem, including your own typos.
Handle different problems differently, and keep the error for its message:
else and finally
elseruns only if no exception happened.finallyruns always, whether or not there was an error. It is the place for cleanup.
Raising your own exceptions
Use raise when your code finds a problem it cannot fix.
Quick quiz
When does the else block of a try statement run?
Custom exceptions
Create your own exception type by inheriting from Exception. Callers can then catch exactly your problem.
Look before you leap, or ask forgiveness?
Python programmers often prefer EAFP, "easier to ask forgiveness than permission": try the operation and handle the failure, rather than checking everything first.
Both are fine. EAFP shines when checking is awkward or when the situation might change between the check and the use.
Try it yourself
Write a function to_int(text, default=0) that converts text to an integer, returning the default if it cannot be converted. Test it with "12", "abc" and "".
Summary
- An exception stops the program unless you handle it. Read a traceback from the bottom up.
try/except SpecificErrorhandles problems,elseruns if nothing failed, andfinallyalways runs.raisesignals a problem, and you can define your own exception classes.- Catch specific exceptions, and avoid a bare
except:.
Lesson complete
+20 XP
Nice work. Keep going while it is fresh.
Sources and further reading