Python except
The except keyword defines a block of code that executes when an error occurs in the associated try block, allowing the program to handle exceptions gracefully.
Syntax
try:
# code that might raise an exception
except:
# code to handle the exception
A specific exception type can also be mentioned as follows:
try:
# code that might raise an exception
except ExceptionType:
# code that runs if the specified exception occurs
Parameters:
ExceptionType(optional): Specifies the type of exception to catch (e.g.,ValueError,ZeroDivisionError).
Return value:
- The except block itself does not return a value.
- It executes code when the associated
tryblock raises a matching exception.
Working of the try-except block
In the try block, code that might cause an error is executed. If an error occurs, the flow jumps to the except block to handle it gracefully. Specifying an exception type in except limits handling to that particular error, allowing for more precise control.
Note: If no exception type is specified, the
exceptblock will catch all exceptions. It’s best to use specific exception types to avoid unintentionally hiding bugs or critical errors.
Example: Handling Index Error with a General except Block
This example attempts to access an invalid index in a list, triggering an error that is caught using a general except block to prevent the program from crashing:
try:array = [0, 1, 2]# list index out of rangen = array[3]except:print('An error occurred.')
The output for this code block will be:
An error occurred.
Codebyte Example
The following example demonstrates how the except block handles dividing by zero error:
Contribute to Docs
- Learn more about how to get involved.
- Edit this page on GitHub to fix an error or make an improvement.
- Submit feedback to let us know how we can improve Docs.
Learn Python on Codecademy
- Looking for an introduction to the theory behind programming? Master Python while learning data structures, algorithms, and more!
- Includes 6 Courses
- With Professional Certification
- Beginner Friendly.75 hours
- Learn the basics of Python 3.12, one of the most powerful, versatile, and in-demand programming languages today.
- With Certificate
- Beginner Friendly.24 hours