Handling Exceptions
In this lesson, you'll learn how to handle exceptions in Python.
We'll cover the following...
Introduction to error handling
Errors happen. A program may try to divide a number by zero, send a message to None
, or read in a file that isn’t there. When this happens, Python will raise an exception.
Every exception type has a name. In Python, there is almost no distinction between an “error” and an “exception.” Either, if not handled, will cause the program to terminate.
If you know where an error is likely to occur, you can deal with it. For example, you might use the input
function to ask the user for an integer. Whatever the user types will be returned as a string, which you can convert to an integer using the int
function. This works —unless the user types in something other than digits, in which case you will get a ValueError
.
To solve this problem, you can use the try-except
, or try-except-finally
statement. It has this general form: ...