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.

Note

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

Syntax

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
try:
    # Works fine
    result = x / y
    print(result)

    # Raises an exception
    x = 10
    y = 0
    result = x / y
    print(result)

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

Output

The output of the above example is:

5.0
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 www.includehelp.com. All rights reserved.