🐍

Understanding Exception Handling in Python

May 21, 2025

Exception Handling in Python

Introduction

  • Errors may occur during program execution, categorized into:
    • Syntax Errors
    • Runtime Errors
    • Logical Errors
  • Exceptions in Python are errors that can be automatically or manually handled.

Syntax Errors

  • Detected when rules of the programming language are violated.
  • Known as parsing errors.
  • Program does not execute until errors are fixed.
  • Python provides error descriptions in both shell and script modes.

Exceptions

  • Errors that occur during execution despite syntactically correct code.
  • Examples: file not found, division by zero.
  • Must be handled to prevent program crashes.

Built-In Exceptions

  • Defined in the Python standard library.
  • Examples of common built-in exceptions:
    • SyntaxError: Incorrect syntax.
    • ValueError: Argument of right type but inappropriate value.
    • IOError: File operation fails.
    • ZeroDivisionError: Division by zero attempt.
    • IndexError: Sequence index out of range.
    • NameError: Variable not defined.
    • TypeError: Wrong data type used.

Raising Exceptions

  • Python raises exceptions when errors occur.
  • Programmers can also raise exceptions using raise and assert statements.
  • Raise Statement: Used to throw exceptions with an optional message.
  • Assert Statement: Validates condition, raises AssertionError if false.

Handling Exceptions

  • Exception handling prevents abrupt program termination.
  • Need for Handling:
    • Separates main logic and error handling code.
    • Allows capturing and managing runtime errors.
  • Process of Handling:
    • Python creates an exception object when an error occurs.
    • Searches for a matching exception handler (call stack).
  • Catching Exceptions:
    • Use try block for code that might throw exceptions.
    • Use except block to handle specific exceptions.
    • Use else block for code execution if no exception occurs.
    • Use finally block for code that runs regardless of exceptions.

Exercises

  1. Justify: Every syntax error is an exception, but not vice versa.
  2. Explain when built-in exceptions like ImportError, IOError, NameError, ZeroDivisionError are raised.
  3. Code to show the use of raise for division by zero.
  4. Use assert to test division expression in previous code.
  5. Define: Exception Handling, Throwing an exception, Catching an exception.
  6. Explain catching exceptions using try and except blocks.
  7. Complete code with appropriate exception handling.
  8. Use math module to demonstrate ValueError handling.
  9. Explain the use of finally clause in exception handling.