Exception Handling in Python

Exception handling in Python is a mechanism that allows you to handle errors and unexpected situations that occur during the execution of a program. It helps in gracefully managing errors and preventing your program from crashing. Python provides a built-in way to handle exceptions using the try, except, else, and finally blocks.

Here's a basic structure of exception handling in Python:

pythonCopy codetry:
    # Code that may raise an exception
    # ...
except ExceptionName1:
    # Code to handle ExceptionName1
    # ...
except ExceptionName2:
    # Code to handle ExceptionName2
    # ...
else:
    # Code that runs if no exceptions occurred in the try block
    # ...
finally:
    # Optional block of code that always runs, regardless of whether an exception occurred or not
    # ...
  • The try block contains the code that might raise an exception.

  • The except block(s) catch and handle specific exceptions. You can have multiple except blocks to handle different types of exceptions.

  • The else block is optional and runs if no exceptions occurred in the try block.

  • The finally block is also optional and runs regardless of whether an exception occurred or not. It is typically used for cleanup actions (e.g., closing files or releasing resources).

Here's an example demonstrating how exception handling works in Python:

pythonCopy codetry:
    x = int(input("Enter a number: "))
    result = 10 / x
    print("Result:", result)
except ZeroDivisionError:
    print("Error: Division by zero!")
except ValueError:
    print("Error: Invalid input! Please enter a valid number.")
else:
    print("No exceptions occurred.")
finally:
    print("Exiting the program.")

In this example:

  • If the user enters 0, a ZeroDivisionError will be raised, and the corresponding except block will handle it.

  • If the user enters a non-numeric value (e.g., "abc"), a ValueError will be raised, and its corresponding except block will handle it.

  • If the user enters a valid number other than 0, the division operation will be performed, and the else block will run.

  • Finally, the finally block will always run, regardless of whether an exception occurred or not.

Exception handling in Python allows you to write robust and reliable code by handling errors gracefully and providing meaningful feedback to users.

Check out more resources:

Comprehension in Python

Multiline Comments in Python