ℹ️ Skipped - page is already crawled
| Filter | Status | Condition | Details |
|---|---|---|---|
| HTTP status | PASS | download_http_code = 200 | HTTP 200 |
| Age cutoff | PASS | download_stamp > now() - 6 MONTH | 0 months ago |
| History drop | PASS | isNull(history_drop_reason) | No drop reason |
| Spam/ban | PASS | fh_dont_index != 1 AND ml_spam_score = 0 | ml_spam_score=0 |
| Canonical | PASS | meta_canonical IS NULL OR = '' OR = src_unparsed | Not set |
| Property | Value |
|---|---|
| URL | https://www.coursera.org/tutorials/python-exception |
| Last Crawled | 2026-04-21 06:26:03 (16 hours ago) |
| First Indexed | 2022-12-08 17:05:33 (3 years ago) |
| HTTP Status Code | 200 |
| Meta Title | How to Catch, Raise, and Print a Python Exception | Coursera |
| Meta Description | Use this tutorial to learn how to handle various Python exceptions. Learn online and earn valuable credentials from top universities like Yale, Michigan, Stanford, and leading companies like Google and IBM. Join Coursera for free and transform ... |
| Meta Canonical | null |
| Boilerpipe Text | 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
Term
Definition
Print
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 back
to 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.
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
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
.
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:
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:
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
Expand to view solution
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)
Expand to view solution
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.
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:
Expand to view solution
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 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
.
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
.
Python errors and exceptions documentation
Python exception handling cheat sheet
Python traceback tutorial
Python syntax tutorial
Python syntax cheat sheet
Being a Python Developer: What They Can Do, Earn, and More
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. |
| Markdown | - [For Individuals](https://www.coursera.org/)
- [For Businesses](https://www.coursera.org/business?utm_content=corp-to-home-for-enterprise&utm_campaign=website&utm_medium=coursera&utm_source=header&utm_term=b-out)
- [For Universities](https://www.coursera.org/campus?utm_content=corp-to-landing-for-campus&utm_campaign=website&utm_medium=coursera&utm_source=header&utm_term=b-out)
- [For Governments](https://www.coursera.org/government?utm_content=corp-to-landing-for-government&utm_campaign=website&utm_medium=coursera&utm_source=header&utm_term=b-out)
Explore
[Degrees](https://www.coursera.org/degrees)
[Log In](https://www.coursera.org/tutorials/python-exception?authMode=login)
[Join for Free](https://www.coursera.org/tutorials/python-exception?authMode=signup)
Join for Free
1. [How to Catch, Raise, and Print a Python Exception]()
# How to Catch, Raise, and Print a Python Exception
Written by Coursera •
Updated on
Aug 13, 2024
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.](https://d3njjcbhbojbot.cloudfront.net/api/utilities/v1/imageproxy/https://images.ctfassets.net/wp1lcwdav1p1/2K5P65z0HNIr4IaFfgMS8Q/71335fe862ff388494200fd17b8e3fd7/GettyImages-1073867510.jpg?w=1500&h=680&q=60&fit=fill&f=faces&fm=jpg&fl=progressive&auto=format%2Ccompress&dpr=1&w=1000)
### On this page
- [Glossary](https://www.coursera.org/tutorials/python-exception#glossary)
- [What is an exception in Python?](https://www.coursera.org/tutorials/python-exception#what-is-an-exception-in-python)
- [Exceptions vs. syntax errors](https://www.coursera.org/tutorials/python-exception#exceptions-vs-syntax-errors)
- [Exception error messages](https://www.coursera.org/tutorials/python-exception#exception-error-messages)
- [How to use try and except in Python to catch exceptions](https://www.coursera.org/tutorials/python-exception#how-to-use-try-and-except-in-python-to-catch-exceptions)
- [Try it yourself](https://www.coursera.org/tutorials/python-exception#try-it-yourself)
- [How to catch a specific exception](https://www.coursera.org/tutorials/python-exception#how-to-catch-a-specific-exception)
- [Try it yourself](https://www.coursera.org/tutorials/python-exception#try-it-yourself-1)
- [Why do we use try and except in Python?](https://www.coursera.org/tutorials/python-exception#why-do-we-use-try-and-except-in-python)
- [How to raise an exception in Python](https://www.coursera.org/tutorials/python-exception#how-to-raise-an-exception-in-python)
- [Try it yourself](https://www.coursera.org/tutorials/python-exception#try-it-yourself-2)
- [How to print an exception in Python](https://www.coursera.org/tutorials/python-exception#how-to-print-an-exception-in-python)
- [Commonly raised built-in exceptions](https://www.coursera.org/tutorials/python-exception#commonly-raised-built-in-exceptions)
- [Key takeaways](https://www.coursera.org/tutorials/python-exception#key-takeaways)
- [Resources](https://www.coursera.org/tutorials/python-exception#resources)
- [Continue building your Python expertise with Coursera.](https://www.coursera.org/tutorials/python-exception#continue-building-your-python-expertise-with-coursera)
**Materials Required:** Latest version of Python ([Python 3](https://www.python.org/downloads/)), 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](https://www.coursera.org/tutorials/python-exception#glossary)
| Term | Definition |
|---|---|
| Print | 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. |
## [What is an exception in Python?](https://www.coursera.org/tutorials/python-exception#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
| 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](https://www.coursera.org/tutorials/python-syntax).
### 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: 
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](https://www.coursera.org/tutorials/python-traceback).
## [How to use try and except in Python to catch exceptions](https://www.coursera.org/tutorials/python-exception#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: 
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
a = 5 b = 0 quotient = a / b
```
```
### SolutionExpand to view solution
PYTHON
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
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
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
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
greeting = word1+word2 print(greeting)
```
```
### SolutionExpand to view solution
PYTHON
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](https://www.coursera.org/tutorials/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](https://www.coursera.org/tutorials/python-exception#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
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
x = -5 if \#YOUR CODE HERE:
```
```
### SolutionExpand to view solution
PYTHON
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](https://www.coursera.org/tutorials/python-exception#how-to-print-an-exception-in-python)
In an exception block, define the exception and use the print() function. Here’s an example:
PYTHON
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](https://www.coursera.org/tutorials/python-exception#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 and exception subclasses in our [Python Exception Handling Cheat Sheet](https://www.coursera.org/tutorials/python-exception-cheat-sheet).
| Exception | Explanation | Hierarchy |
|---|---|---|
| `AttributeError` | When an [attribute reference](https://docs.python.org/3/reference/expressions.html#attribute-references) 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()`](https://docs.python.org/3/library/functions.html#input) function reaches an EOF condition without reading any data. | Inherits from `Exception`. |
| `ImportError` | Raised when an [import statement](https://docs.python.org/3/reference/simple_stmts.html#import) 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](https://docs.python.org/3/library/sys.html#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`. |
## [Key takeaways](https://www.coursera.org/tutorials/python-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](https://www.coursera.org/tutorials/python-exception#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](http://www.pythonweekly.com/) or connecting with peers by joining the [Python programming Slack channel](https://pyslackers.com/web).
- [Python errors and exceptions documentation](https://docs.python.org/3/tutorial/errors.html)
- [Python exception handling cheat sheet](https://www.coursera.org/tutorials/python-exception-cheat-sheet)
- [Python traceback tutorial](https://www.coursera.org/tutorials/python-traceback)
- [Python syntax tutorial](https://www.coursera.org/tutorials/python-syntax)
- [Python syntax cheat sheet](https://www.coursera.org/tutorials/python-syntax-cheat-sheet)
- [Being a Python Developer: What They Can Do, Earn, and More](https://www.coursera.org/articles/python-developer)
## [Continue building your Python expertise with Coursera.](https://www.coursera.org/tutorials/python-exception#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](https://www.coursera.org/projects/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](https://www.coursera.org/specializations/python-3-programming) from the University of Michigan.
***
Written by Coursera •
Updated on
Aug 13, 2024
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.
### On this page
- [Glossary](https://www.coursera.org/tutorials/python-exception#glossary)
- [What is an exception in Python?](https://www.coursera.org/tutorials/python-exception#what-is-an-exception-in-python)
- [Exceptions vs. syntax errors](https://www.coursera.org/tutorials/python-exception#exceptions-vs-syntax-errors)
- [Exception error messages](https://www.coursera.org/tutorials/python-exception#exception-error-messages)
- [How to use try and except in Python to catch exceptions](https://www.coursera.org/tutorials/python-exception#how-to-use-try-and-except-in-python-to-catch-exceptions)
- [Try it yourself](https://www.coursera.org/tutorials/python-exception#try-it-yourself)
- [How to catch a specific exception](https://www.coursera.org/tutorials/python-exception#how-to-catch-a-specific-exception)
- [Try it yourself](https://www.coursera.org/tutorials/python-exception#try-it-yourself-1)
- [Why do we use try and except in Python?](https://www.coursera.org/tutorials/python-exception#why-do-we-use-try-and-except-in-python)
- [How to raise an exception in Python](https://www.coursera.org/tutorials/python-exception#how-to-raise-an-exception-in-python)
- [Try it yourself](https://www.coursera.org/tutorials/python-exception#try-it-yourself-2)
- [How to print an exception in Python](https://www.coursera.org/tutorials/python-exception#how-to-print-an-exception-in-python)
- [Commonly raised built-in exceptions](https://www.coursera.org/tutorials/python-exception#commonly-raised-built-in-exceptions)
- [Key takeaways](https://www.coursera.org/tutorials/python-exception#key-takeaways)
- [Resources](https://www.coursera.org/tutorials/python-exception#resources)
- [Continue building your Python expertise with Coursera.](https://www.coursera.org/tutorials/python-exception#continue-building-your-python-expertise-with-coursera)
## Learn without limits

Join for Free
Coursera Footer
## Skills
- [Accounting](https://www.coursera.org/courses?query=accounting)
- [Artificial Intelligence (AI)](https://www.coursera.org/courses?query=artificial%20intelligence)
- [Cybersecurity](https://www.coursera.org/courses?query=cybersecurity)
- [Data Analytics](https://www.coursera.org/courses?query=data%20analytics)
- [Digital Marketing](https://www.coursera.org/courses?query=digital%20marketing)
- [Human Resources (HR)](https://www.coursera.org/courses?query=hr)
- [Microsoft Excel](https://www.coursera.org/courses?query=microsoft%20excel)
- [Project Management](https://www.coursera.org/courses?query=project%20management)
- [Python](https://www.coursera.org/courses?query=python)
- [SQL](https://www.coursera.org/courses?query=sql)
## Professional Certificates
- [Google AI Certificate](https://www.coursera.org/professional-certificates/google-ai)
- [Google Cybersecurity Certificate](https://www.coursera.org/professional-certificates/google-cybersecurity)
- [Google Data Analytics Certificate](https://www.coursera.org/professional-certificates/google-data-analytics)
- [Google IT Support Certificate](https://www.coursera.org/professional-certificates/google-it-support)
- [Google Project Management Certificate](https://www.coursera.org/professional-certificates/google-project-management)
- [Google UX Design Certificate](https://www.coursera.org/professional-certificates/google-ux-design)
- [IBM AI Engineering Certificate](https://www.coursera.org/professional-certificates/ai-engineer)
- [IBM AI Product Manager Certificate](https://www.coursera.org/professional-certificates/ibm-ai-product-manager)
- [IBM Data Science Certificate](https://www.coursera.org/professional-certificates/ibm-data-science)
- [Intuit Academy Bookkeeping Certificate](https://www.coursera.org/professional-certificates/intuit-bookkeeping)
## Courses & Specializations
- [AI Essentials Specialization](https://www.coursera.org/specializations/ai-essentials-google)
- [AI For Business Specialization](https://www.coursera.org/specializations/ai-for-business-wharton)
- [AI For Everyone Course](https://www.coursera.org/learn/ai-for-everyone)
- [AI in Healthcare Specialization](https://www.coursera.org/specializations/ai-healthcare)
- [Deep Learning Specialization](https://www.coursera.org/specializations/deep-learning)
- [Excel Skills for Business Specialization](https://www.coursera.org/specializations/excel)
- [Financial Markets Course](https://www.coursera.org/learn/financial-markets-global)
- [Machine Learning Specialization](https://www.coursera.org/specializations/machine-learning-introduction)
- [Prompt Engineering for ChatGPT Course](https://www.coursera.org/learn/prompt-engineering)
- [Python for Everybody Specialization](https://www.coursera.org/specializations/python)
## Career Resources
- [Career Aptitude Test](https://www.coursera.org/resources/career-quiz)
- [CAPM Certification Requirements](https://www.coursera.org/articles/capm-certification-guide)
- [CompTIA A+ Certification Requirements](https://www.coursera.org/articles/what-is-the-comptia-a-certification-what-to-know)
- [CompTIA Security+ Certification Requirements](https://www.coursera.org/articles/what-is-the-comptia-security-plus-certification)
- [Essential IT Certifications](https://www.coursera.org/articles/essential-it-certifications-entry-level-and-beginner)
- [Free IT Certifications and Courses](https://www.coursera.org/articles/free-it-certifications)
- [High-Income Skills to Learn](https://www.coursera.org/articles/high-income-skills)
- [How to Learn Artificial Intelligence](https://www.coursera.org/articles/how-to-learn-artificial-intelligence)
- [PMP Certification Requirements](https://www.coursera.org/articles/the-pmp-certification-a-guide-to-getting-started)
- [Popular Cybersecurity Certifications](https://www.coursera.org/articles/popular-cybersecurity-certifications)
## Coursera
- [About](https://www.coursera.org/about)
- [What We Offer](https://www.coursera.org/about/how-coursera-works/)
- [Leadership](https://www.coursera.org/about/leadership)
- [Careers](https://careers.coursera.com/)
- [Catalog](https://www.coursera.org/browse)
- [Coursera Plus](https://www.coursera.org/courseraplus)
- [Professional Certificates](https://www.coursera.org/professional-certificates)
- [MasterTrack® Certificates](https://www.coursera.org/mastertrack)
- [Degrees](https://www.coursera.org/degrees)
- [For Enterprise](https://www.coursera.org/business?utm_campaign=website&utm_content=corp-to-home-footer-for-enterprise&utm_medium=coursera&utm_source=enterprise)
- [For Government](https://www.coursera.org/government?utm_campaign=website&utm_content=corp-to-home-footer-for-government&utm_medium=coursera&utm_source=enterprise)
- [For Campus](https://www.coursera.org/campus?utm_campaign=website&utm_content=corp-to-home-footer-for-campus&utm_medium=coursera&utm_source=enterprise)
- [Become a Partner](https://partnerships.coursera.org/?utm_medium=coursera&utm_source=partnerships&utm_campaign=website&utm_content=corp-to-home-footer-become-a-partner)
- [Social Impact](https://www.coursera.org/social-impact)
- [Free Courses](https://www.coursera.org/courses?query=free)
- [Share your Coursera learning story](https://airtable.com/appxSsG2Dz9CjSpF8/pagCDDP2Uinw59CNP/form?prefill_utm_source=product&prefill_utm_campaign=seo_footer&prefill_utm_medium=written)
## Community
- [Learners](https://www.coursera.community/)
- [Partners](https://www.coursera.org/partners)
- [Beta Testers](https://www.coursera.support/s/article/360000152926-Become-a-Coursera-beta-tester)
- [Blog](https://blog.coursera.org/)
- [The Coursera Podcast](https://open.spotify.com/show/58M36bneU7REOofdPZxe6A)
- [Tech Blog](https://medium.com/coursera-engineering)
## More
- [Press](https://www.coursera.org/about/press)
- [Investors](https://investor.coursera.com/)
- [Terms](https://www.coursera.org/about/terms)
- [Privacy](https://www.coursera.org/about/privacy)
- [Help](https://learner.coursera.help/hc)
- [Accessibility](https://learner.coursera.help/hc/articles/360050668591-Accessibility-Statement)
- [Contact](https://www.coursera.org/about/contact)
- [Articles](https://www.coursera.org/articles)
- [Directory](https://www.coursera.org/directory)
- [Affiliates](https://www.coursera.org/about/affiliates)
- [Modern Slavery Statement](https://coursera_assets.s3.amazonaws.com/footer/Modern+Slavery+Statement+\(approved+March+26%2C+2025\).pdf)
- [Cookies Preference Center](https://www.coursera.org/about/cookies-manage)
Learn Anywhere
[](https://itunes.apple.com/app/apple-store/id736535961?pt=2334150&ct=Coursera%20Web%20Promo%20Banner&mt=8)
[](http://play.google.com/store/apps/details?id=org.coursera.android)

© 2026 Coursera Inc. All rights reserved.
- [](https://www.facebook.com/Coursera)
- [](https://www.linkedin.com/company/coursera)
- [](https://twitter.com/coursera)
- [](https://www.youtube.com/user/coursera)
- [](https://www.instagram.com/coursera/)
- [](https://www.tiktok.com/@coursera) |
| Readable Markdown | **Materials Required:** Latest version of Python ([Python 3](https://www.python.org/downloads/)), 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](https://www.coursera.org/tutorials/python-exception#glossary)
| Term | Definition |
|---|---|
| Print | 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. |
## [What is an exception in Python?](https://www.coursera.org/tutorials/python-exception#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
| 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](https://www.coursera.org/tutorials/python-syntax).
### 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: 
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](https://www.coursera.org/tutorials/python-traceback).
## [How to use try and except in Python to catch exceptions](https://www.coursera.org/tutorials/python-exception#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: 
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
```
```
### Expand to view solution
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
```
```
You can also specify multiple exceptions at once:
PYTHON
```
```
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
```
```
### 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
```
```
### Expand to view solution
**Learn more:** [How to Use a Python If-Else Statement](https://www.coursera.org/tutorials/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.
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
```
```
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
```
```
### Expand to view solution
## [How to print an exception in Python](https://www.coursera.org/tutorials/python-exception#how-to-print-an-exception-in-python)
In an exception block, define the exception and use the print() function. Here’s an example:
PYTHON
```
```
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](https://www.coursera.org/tutorials/python-exception#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 and exception subclasses in our [Python Exception Handling Cheat Sheet](https://www.coursera.org/tutorials/python-exception-cheat-sheet).
| Exception | Explanation | Hierarchy |
|---|---|---|
| `AttributeError` | When an [attribute reference](https://docs.python.org/3/reference/expressions.html#attribute-references) 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()`](https://docs.python.org/3/library/functions.html#input) function reaches an EOF condition without reading any data. | Inherits from `Exception`. |
| `ImportError` | Raised when an [import statement](https://docs.python.org/3/reference/simple_stmts.html#import) 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](https://docs.python.org/3/library/sys.html#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`. |
## [Key takeaways](https://www.coursera.org/tutorials/python-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](https://www.coursera.org/tutorials/python-exception#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](http://www.pythonweekly.com/) or connecting with peers by joining the [Python programming Slack channel](https://pyslackers.com/web).
- [Python errors and exceptions documentation](https://docs.python.org/3/tutorial/errors.html)
- [Python exception handling cheat sheet](https://www.coursera.org/tutorials/python-exception-cheat-sheet)
- [Python traceback tutorial](https://www.coursera.org/tutorials/python-traceback)
- [Python syntax tutorial](https://www.coursera.org/tutorials/python-syntax)
- [Python syntax cheat sheet](https://www.coursera.org/tutorials/python-syntax-cheat-sheet)
- [Being a Python Developer: What They Can Do, Earn, and More](https://www.coursera.org/articles/python-developer)
## [Continue building your Python expertise with Coursera.](https://www.coursera.org/tutorials/python-exception#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](https://www.coursera.org/projects/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](https://www.coursera.org/specializations/python-3-programming) from the University of Michigan. |
| Shard | 97 (laksa) |
| Root Hash | 1995246928644532097 |
| Unparsed URL | org,coursera!www,/tutorials/python-exception s443 |