How to Handle Exceptions in Python Using try and except?

Exception handling in Python is performed using the try and except blocks. This mechanism allows you to catch and handle errors gracefully without stopping the execution of your program.

Basic Syntax

try:
    # Code that may raise an exception
except ExceptionType:
    # Code to handle the exception

Example: Handling ZeroDivisionError

try:
    result = 10 / 0
except ZeroDivisionError:
    print("Cannot divide by zero!")

Catching Multiple Exceptions

You can catch multiple exceptions by specifying a tuple of exception types:

try:
    # Code that may raise an exception
except (TypeError, ValueError):
    # Handle TypeError and ValueError

Using else and finally Blocks

else runs if no exceptions occur, and finally runs no matter what:

try:
    result = 10 / 2
except ZeroDivisionError:
    print("Cannot divide by zero!")
else:
    print(f"Result is {result}")
finally:
    print("Execution complete.")

Accessing Exception Details

You can access exception details using the as keyword:

try:
    result = int('abc')
except ValueError as e:
    print(f"ValueError occurred: {e}")

Creating Custom Exceptions

You can define your own exception classes:

class MyCustomError(Exception):
    pass

try:
    raise MyCustomError("An error occurred")
except MyCustomError as e:
    print(e)

Conclusion

Using try and except blocks in Python allows for robust error handling, ensuring your programs can handle unexpected situations gracefully.

Leave a Reply

Your email address will not be published. Required fields are marked *