Try and Except Statement in Python - Catching Exceptions

By IncludeHelp Last updated : February 7, 2024

The try and except statement in Python is the combination of two blocks try and except. It is used to catch and handle exceptions. The code statements that may raise an exception should be written in try block and the exceptions should be written inside the except block.


The try and except are built-in keywords and they are also called clauses.


Below is the syntax of try and except statements in Python:

Try and Except Statement Example

The example below demonstrates the try and except statement:

# Python program to demonstrate an example of
# Try and Except Statement Example

# Declare two variables
x = 10
y = 2

# Try block
    # Works fine
    result = x / y

    # Raises an exception
    x = 10
    y = 0
    result = x / y

# Except block
    print("Error Python : [ZeroDivisionError: division by zero]")


The output of the above example is:

Error Python : [ZeroDivisionError: division by zero]

To understand the above below, you should have the basic knowledge of the following Python topics:


Comments and Discussions!

Load comments ↻

Copyright © 2024 All rights reserved.