How to Catch, Raise, and Print a Python Exception

Written by Coursera • Updated on

Use this tutorial to learn how to handle various Python exceptions.

[Featured image] A software engineer with long hair and sunglasses on her head works to resolve a Python exception in her code.

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.

Glossary

TermDefinition
Printprint() is a function that converts a specified object into text and sends it to the screen or other standard output device.
Raiseraise() is a function that interrupts the normal execution process of a program. It signals the presence of special circumstances such as exceptions or errors.
ThrowThe term “throw” is used synonymously with “raise.” However, “throw” is not a Python keyword.
TracebackWhen 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 ErrorSyntax is the set of rules that defines the structure of a language. A syntax error indicates 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.

What is an exception in Python?

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 vs. syntax errors

ExceptionsSyntax errors
Change the normal flow of a programStop the execution of a program entirely
Occur during execution, and are not always inoperableGenerated during parsing, when source code is translated into byte code
Can be handled at runtimeCannot 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.

Exception error messages

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: type error

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.

How to use try and except in Python to catch exceptions

To catch a Python exception, use a try statement. A try statement includes:

  • The keyword try
  • A colon
  • The code block that may cause an error

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: Try Except

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.

Try it yourself

How would you revise this code with try and except to avoid generating a traceback?

PYTHON
1
2
3
a = 5
b = 0
quotient = a / b

PYTHON
1
2
3
4
5
6
7
a = 5
b = 0

try:
  quotient = a / b
except:
  print("You cannot divide by zero")

Need help?

What if the try block executes without error? If you want the program to take action even when the try block succeeds, use an else block after the except block.

How to catch a specific exception

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:

PYTHON
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:

PYTHON
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:

PYTHON
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")

Try it yourself

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.

PYTHON
1
2
greeting = word1+word2
print(greeting)

PYTHON
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

Why do we use try and except in Python?

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.

How to raise an exception in Python

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:

PYTHON
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.

Try it yourself

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?

PYTHON
1
2
3
x = -5

if #YOUR CODE HERE:

PYTHON
1
2
3
4
x = -5

if x < 0:
    raise Exception("Sorry, please enter a number greater than or equal to 0")

How to print an exception in Python

In an exception block, define the exception and use the print() function. Here’s an example:

PYTHON
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?

Why isn’t Python printing my exception? If you’re having trouble getting your exception error message to print, double check the code inside your try-except block. It’s possible that the exception is not being raised, causing the code to run without hitting the exception handler.

Commonly raised built-in exceptions

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 in our Python Exception Handling Cheat Sheet.

ExceptionExplanationHierarchy
AttributeErrorWhen an attribute reference or assignment fails, this Python exception is raised. Inherits from Exception.
EOFErrorEOF stands for end-of-file. This exception is raised when an input() function reaches an EOF condition without reading any data.Inherits from Exception.
ImportErrorRaised 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.
ModuleNotFoundErrorAlso 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.
ZeroDivisionErrorPython 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.
IndexErrorThis exception occurs if a sequence subscript is out of range.Inherits from Exception.
KeyErrorRaised when a mapping key or, dictionary key, is not found in the existing set of keys.Inherits from Exception.
MemoryErrorRaised when there is not enough memory for the current operation. This exception can be addressed by deleting other objects. Inherits from Exception.
NameErrorWhen 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.
ConnectionErrorBase class for issues related to connection.Inherits from Exception, belongs to the subclass of OS exceptions.
TypeErrorIf an operation or function is applied to an object of improper type, Python raises this exception.Inherits from Exception.
ValueErrorRaised 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.

Key takeaways

  • Exceptions occur during a program’s execution.
  • There are built-in exceptions and user-defined exceptions.
  • Base classes are not to be inherited by user-defined classes.
  • You can use try and except in Python to catch exceptions.

Resources

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.

Continue building your Python expertise with Coursera.

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.


Written by Coursera • Updated on

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.

Learn without limits