🐍 Python Q15 / 170

What is exception handling in Python?

AI-Powered Answer ✓ Answered

Exception handling in Python is a mechanism that allows you to manage errors that occur during the execution of a program. These errors, known as exceptions, disrupt the normal flow of the program. By handling them, you can prevent your program from crashing and ensure it continues to run smoothly or fails gracefully.

When an error occurs, Python raises an exception. If this exception is not caught and handled, the program will terminate abruptly and display a traceback. Exception handling provides a structured way to respond to these runtime errors, making your code more robust and user-friendly.

Keywords for Exception Handling

Python uses specific keywords to implement exception handling. The primary constructs are try and except, optionally followed by else and finally.

  • try block: Contains the code that might raise an exception. Python attempts to execute the code inside this block.
  • except block: Catches and handles specific exceptions that occur in the try block. You can specify the type of exception to catch.
  • else block: Executes if no exception occurred in the try block. It must follow all except blocks.
  • finally block: Executes unconditionally, regardless of whether an exception occurred or was handled. It's typically used for cleanup operations.

Basic Syntax

python
try:
    # Code that might raise an exception
    result = 10 / 0
except ZeroDivisionError:
    # Code to handle the specific exception
    print("Error: Cannot divide by zero!")
print("Program continues after handling the exception.")

Handling Multiple Exceptions

python
try:
    num = int("abc") # This will raise a ValueError
    # my_list = [1, 2]
    # print(my_list[3]) # This would raise an IndexError
except ValueError:
    print("Error: Invalid number format.")
except IndexError:
    print("Error: List index out of range.")
except Exception as e: # Generic exception handler (catch-all)
    print(f"An unexpected error occurred: {e}")

`else` and `finally` blocks

python
try:
    file = open("myfile.txt", "r")
    content = file.read()
    print(content)
except FileNotFoundError:
    print("Error: The file was not found.")
else:
    print("File read successfully without exceptions.")
finally:
    # This block always executes
    if 'file' in locals() and not file.closed:
        file.close()
        print("File closed.")
    elif 'file' in locals() and file.closed:
        print("File was already closed (e.g., if open() failed).")
    else:
        print("File variable was not created or assigned.")

Common Built-in Exceptions

  • ValueError: Raised when an operation receives an argument of correct type but inappropriate value (e.g., int('abc')).
  • TypeError: Raised when an operation or function is applied to an object of inappropriate type (e.g., 'hello' + 5).
  • NameError: Raised when a local or global name is not found (e.g., referencing an undefined variable).
  • IndexError: Raised when a sequence subscript (index) is out of range (e.g., my_list[10] for a list of size 5).
  • KeyError: Raised when a dictionary key is not found (e.g., my_dict['non_existent_key']).
  • FileNotFoundError: Raised when a file or directory is requested but doesn't exist.
  • ZeroDivisionError: Raised when the second argument of a division or modulo operation is zero.

By strategically using try, except, else, and finally blocks, developers can create robust Python applications that can gracefully recover from errors, provide meaningful feedback to users, and ensure resource cleanup.