Camkode
Camkode

How to Handle Exceptions in Python

Posted by Kosal

How to Handle Exceptions in Python

Handling exceptions in Python is essential for writing robust and reliable code. You can handle exceptions using the try, except, else, and finally blocks. Here's a basic structure:

try:
    # Code block where an exception might occur
    # Example: division by zero
    result = 10 / 0
except ExceptionType:
    # Code block to handle the exception
    # Example: division by zero exception
    print("An error occurred")
else:
    # Code block that executes if no exception occurs
    # Example: no exception occurred
    print("No error occurred")
finally:
    # Code block that always executes, regardless of whether an exception occurred
    # Example: cleanup or resource release
    print("Finally block executed")

Here's a breakdown of each block:

  1. try: This block contains the code that might raise an exception.
  2. except: This block catches and handles the exception. You can specify which type of exception to catch (or catch all exceptions using Exception), or you can omit the exception type to catch all exceptions.
  3. else (optional): This block executes if no exceptions occur in the try block.
  4. finally (optional): This block always executes, regardless of whether an exception occurred. It's typically used for cleanup or releasing resources.

Here's a simple example:

try:
    result = 10 / 0
except ZeroDivisionError:
    print("Cannot divide by zero")
else:
    print("Division successful")
finally:
    print("Cleanup")

Output:

Cannot divide by zero
Cleanup

Remember, it's essential to handle exceptions gracefully to prevent unexpected crashes and improve the reliability of your code.