Different Syntaxes for try-except block in Python

Different Syntaxes for try-except block in Python

In Python, the try and except blocks are used to handle exceptions. There are several syntaxes that you can use depending on your needs. Here are some of the different ways to use them:

1. Basic Try-Except

The most basic form, used to catch all exceptions:

try:
    # Code that might raise an exception
    x = 1 / 0
except:
    # Code to execute if an exception occurs
    print("An error occurred")
        

2. Catching Specific Exception Types

You can specify the type of exception you want to catch:

try:
    # Code that might raise an exception
    x = int("abc")
except ValueError:
    # Handles ValueError
    print("Invalid input")
        

3. Multiple Except Blocks

You can catch multiple specific exceptions using multiple except blocks:

try:
    # Code that might raise an exception
    x = 1 / 0
except ZeroDivisionError:
    print("Cannot divide by zero")
except ValueError:
    print("Invalid value")
        

4. Catching Multiple Exceptions in One Block

You can catch multiple exceptions in a single except block by passing a tuple:

try:
    # Code that might raise an exception
    x = 1 / 0
except (ZeroDivisionError, ValueError) as e:
    print(f"Error: {e}")
        

5. Using Else Block

The else block runs if no exception was raised in the try block:

try:
    # Code that might raise an exception
    x = 5 / 1
except ZeroDivisionError:
    print("Cannot divide by zero")
else:
    print("No error occurred, result:", x)
        

6. Using Finally Block

The finally block runs no matter what, whether an exception is raised or not:

try:
    # Code that might raise an exception
    x = 5 / 1
except ZeroDivisionError:
    print("Cannot divide by zero")
finally:
    print("This block runs no matter what")
        

7. Catching Exception and Accessing Exception Details

You can capture the exception object and access its details:

try:
    # Code that might raise an exception
    x = int("abc")
except ValueError as e:
    print(f"Caught an exception: {e}")
        

8. Raising Exceptions Manually

You can also raise exceptions manually using raise:

try:
    x = int("abc")
except ValueError:
    print("Invalid input")
    raise  # Re-raises the last exception
        

9. Nested Try-Except Blocks

You can have try-except blocks inside other try-except blocks:

try:
    # Code that might raise an exception
    try:
        x = 1 / 0
    except ZeroDivisionError:
        print("Inner ZeroDivisionError caught")
except:
    print("Outer exception caught")
        

10. Try-Except with Context Manager

You can use try-except with context managers (like open for file handling):

try:
    with open("file.txt", "r") as file:
        data = file.read()
except FileNotFoundError as e:
    print(f"File not found: {e}")
        

These are the most common ways to structure try-except blocks in Python. You can mix and match these syntaxes depending on the complexity of the errors you're handling.

To view or add a comment, sign in

More articles by Swapnil Singh

Insights from the community

Others also viewed

Explore topics