Skip to main content

Python Tutorial 7.3 - Robust Exception Handling

Welcome to the “Robust Exception Handling” tutorial!


Overview

Advanced use of try, except, else, finally blocks and custom exceptions.

Syntax Structure

try:
    # code that may raise
except (TypeError, ValueError) as e:
    # handle specific exceptions
except Exception as e:
    # handle any other exception
else:
    # runs if no exception
finally:
    # runs no matter what

Example

class MyError(Exception):
    """Custom exception type."""
    pass

def divide(a, b):
    try:
        return a / b
    except ZeroDivisionError:
        print("Cannot divide by zero!")
    except Exception as e:
        print(f"Unexpected error: {e}")
    else:
        print("Division successful.")
    finally:
        print("Execution completed.")

divide(10, 0)

Key Takeaways

  • Catch multiple exceptions separately.
  • Use else for code when no exception occurs.
  • Use finally for cleanup (e.g., closing resources).
  • Define custom exceptions by subclassing Exception.

Happy coding!

Comments