Use this tutorial to learn how to handle various Python exceptions.
Materials Required: Latest version of Python (Python 3), an integrated development environment (IDE) of your choice (or terminal), stable internet connection
Prerequisites/helpful expertise: Basic knowledge of Python and programming concepts
Exceptions are extremely useful tools for Python programmers. They enable you to handle errors, write more readable code, and simulate implementation consequences. By the end of this tutorial, you will be able to use Python exceptions to code more efficiently.
Term | Definition |
---|---|
print() is a function that converts a specified object into text and sends it to the screen or other standard output device. | |
Raise | raise() is a function that interrupts the normal execution process of a program. It signals the presence of special circumstances such as exceptions or errors. |
Throw | The term “throw” is used synonymously with “raise.” However, “throw” is not a Python keyword. |
Traceback | When an error occurs, you can trace it backto the source using this Python module. A traceback reports the function calls made at a given point in your code. Tracebacks are read from the bottom upward. |
Syntax Error | Syntax is the set of rules that defines the structure of a language. A syntax error indicates an invalid input. You have entered a character or string that the program’s interpreter cannot understand. |
try | "Try" is a Python keyword. It enables you to test a code block for errors. |
except | "Except" is a Python keyword that is used to handle exceptions arising in the previous try clause. |
Exceptions are also known as logical errors. They occur during a program’s execution. Rather than allowing the program to crash when an error is detected, Python generates an exception you can handle. It’s comparable to the way an iPhone displays a temperature warning when your phone gets too hot. Instead of allowing the phone to overheat, it stops itself from functioning and prompts you to resolve the issue by cooling it down. Similarly, Python exceptions halt the program and provide you with an opportunity to resolve the error instead of crashing.
There are two types of Python exceptions:
1. User-defined exceptions: User-defined exceptions are custom exceptions created by programmers. They enable you to enforce restrictions or consequences on certain functions, values, or variables.
2. Built-in exceptions: There are many different types of exceptions pre-defined by Python. These are called built-in exceptions. You can find a reference table defining each type of built-in exception at the bottom of this page or our Python Exception Handling Cheat Sheet.
Exceptions | Syntax errors |
---|---|
Change the normal flow of a program | Stop the execution of a program entirely |
Occur during execution, and are not always inoperable | Generated during parsing, when source code is translated into byte code |
Can be handled at runtime | Cannot be handled |
You can learn more about Python syntax errors in the previous tutorial in this series, How to Identify and Resolve Python Syntax Errors.
When an exception is raised in your code, Python prints a traceback. Tracebacks provide you with information regarding why an error may have occurred. Here is an example:
The last line in the code block shown above indicates the type of exception that has occurred. You can learn more about tracebacks with the next tutorial in this series, How to Retrieve, Print, Read, and Log a Python Traceback.
To catch a Python exception, use a try statement. A try statement includes:
Next, write the code you want to handle the exceptions in the except clause. This allows you to tell the program which operations to perform once the exception in the try block has been caught. Here’s an example:
In the above example, the code beneath the try
keyword throws a TypeError, since you cannot add a string type to an integer type. This prompts the interpreter to run the except
block instead.
How would you revise this code with try and except to avoid generating a traceback?
1 2 3
a = 5 b = 0 quotient = a / b
1 2 3 4 5 6 7
a = 5 b = 0 try: quotient = a / b except: print("You cannot divide by zero")
Need help?
The method above demonstrates how to catch all exceptions in Python. However, many different types of errors can arise from the code you put inside the try block. If you don’t specify which exceptions a particular except clause should catch, it will handle each one the same way. You can address this issue in a few ways. For example, you can anticipate the errors that may occur and add corresponding except blocks for each one.
Here’s an example:
1 2 3 4 5 6 7 8 9 10 11 12
a = 5 b = "zero" try: quotient = a / b print(quotient) except ZeroDivisionError: print("You cannot divide by zero") except TypeError: print("You must convert strings to floats or integers before dividing") except NameError: print("A variable you're trying to use does not exist")
You can also specify multiple exceptions at once:
1 2 3 4 5 6 7 8
a = 5 b = "zero" try: quotient = a / b print(quotient) except (ZeroDivisionError, TypeError): print("This division is impossible")
Suppose you want to implement a few special cases but handle all other exceptions the same. In that case, you can create an except block to handle all other exceptions:
1 2 3 4 5 6 7 8 9 10
a = 5 b = 0 try: quotient = a / c print(quotient) except (ZeroDivisionError, TypeError): print("You cannot divide by zero and variables must be floats or integers") except: print("Other error")
Add an except statement to this code that prints "You can only concatenate strings to strings" if there's a TypeError and "Something else went wrong" for any other type of error.
1 2
greeting = word1+word2 print(greeting)
1 2 3 4 5 6 7
try: greeting = word1+word2 print(greeting) except TypeError: print("You can only concatenate strings to strings") except: print("Something else went wrong")
Learn more: How to Use a Python If-Else Statement
Python attempts to execute the statements within the try clause first. If an error occurs, it skips the rest of the clause and prompts the program to follow your except clause instructions. Instead of manually instructing the program each time it encounters a given error, it can handle it automatically. Additionally, handling exceptions this way enables you to replace the interpreter’s error message with a much more user friendly one.
The raise statement allows you to force an error to occur. You can define both the type of error and the text that prints to the user. Note that the argument to raise must either be an exception instance or a subclass deriving from exception
.
Example: Suppose you want to raise an error and stop the program if a variable is anything but a string. In that case, you could write the following exception:
1 2 3 4
x = -5 if not type(x) is str: raise TypeError("Sorry, only strings are allowed")
In the code block above, TypeError
is the specified error. It has been set to occur anytime the variable x
is not a string. The text inside the parentheses represents your chosen text to print to the user.
How would you raise an exception that prints "Sorry, please enter a number greater than or equal to 0" if x is a negative number?
1 2 3
x = -5 if #YOUR CODE HERE:
1 2 3 4
x = -5 if x < 0: raise Exception("Sorry, please enter a number greater than or equal to 0")
In an exception block, define the exception and use the print() function. Here’s an example:
1 2 3 4 5 6 7 8
a = 5 b = 0 try: quotient = a / b print(quotient) except Exception as X: print(X)
Need help?
The chart below outlines a few of the most commonly encountered exceptions in Python. You can view a more comprehensive list of built-in Python exceptions and exception subclasses in our Python Exception Handling Cheat Sheet.
Exception | Explanation | Hierarchy |
---|---|---|
AttributeError | When an attribute reference or assignment fails, this Python exception is raised. | Inherits from Exception . |
EOFError | EOF stands for end-of-file. This exception is raised when an input() function reaches an EOF condition without reading any data. | Inherits from Exception . |
ImportError | Raised when an import statement struggles to load a module. Can also be raised when a “from list” in from...import includes a name it cannot find. | Inherits from Exception . |
ModuleNotFoundError | Also raised by import. Occurs when a module cannot be located or when None is found in sys.modules. | Inherits from Exception and is a subclass of ImportError . |
ZeroDivisionError | Python raises this type of error when the second argument of a modulo operation or a division is 0. | Inherits from Exception and is a subclass of ArithmeticError . |
IndexError | This exception occurs if a sequence subscript is out of range. | Inherits from Exception . |
KeyError | Raised when a mapping key or, dictionary key, is not found in the existing set of keys. | Inherits from Exception . |
MemoryError | Raised when there is not enough memory for the current operation. This exception can be addressed by deleting other objects. | Inherits from Exception . |
NameError | When a global or local name cannot be found, this type of error is raised. The conditions for this exception only apply to unqualified names. | Inherits from Exception . |
ConnectionError | Base class for issues related to connection. | Inherits from Exception , belongs to the subclass of OS exceptions. |
TypeError | If an operation or function is applied to an object of improper type, Python raises this exception. | Inherits from Exception . |
ValueError | Raised when an operation or function receives the right type of argument but the wrong value and it cannot be matched by a more specific exception. | Inherits from Exception . |
Another way to stay current on Python releases and tips is to get involved with the Python community. Consider subscribing to the free Python email newsletter or connecting with peers by joining the Python programming Slack channel.
Take the next step in mastering the Python language by completing a Guided Project like Testing and Debugging Python. For a deeper exploration of the language that rewards your work with a certificate, consider an online course like Python 3 Programming from the University of Michigan.
This content has been made available for informational purposes only. Learners are advised to conduct additional research to ensure that courses and other credentials pursued meet their personal, professional, and financial goals.