Exception Handling

Exception handling in Python allows your program to respond to unexpected errors gracefully using the try, except, finally, and else blocks.

Basic Structure

try:
  # Code that may raise an exception
except ExceptionType:
  # Code to handle the exception
else:
  # Code to run if no exception occurs
finally:
  # Code that always runs, regardless of exceptions

In this structure:

Common Exception Types

A few of the exception types are provided in this file : exceptiontypes.html

For common exceptions official reference click official reference

Example 1: Basic try-except

try:
  x = 1 / 0
except ZeroDivisionError:
  print("Cannot divide by zero")

Example 2: Catching multiple exceptions

try:
  int("abc")
except (ValueError, TypeError) as e:
  print(f"Error: {e}")

Example 3: Using else block

try:
  x = 10
except:
  print("Error")
else:
  print("No error")

Example 4: Finally block

try:
  f = open("file.txt")
except FileNotFoundError:
  print("File not found")
finally:
  print("Finished")

Example 5: Raising exceptions manually

x = -1
if x < 0:
  raise ValueError("Negative value not allowed")

Example 6: Custom exception class

class MyError(Exception):
  pass
raise MyError("Something went wrong")

Example 7: Nested try-except

try:
  try:
    x = 1 / 0
  except ZeroDivisionError:
    print("Inner error")
except:
  print("Outer error")

Example 8: Using assert

x = 5
assert x > 10, "x should be greater than 10"

Example 9: Re-raising exception

try:
  raise ValueError("Invalid input")
except ValueError as e:
  print("Caught")
  raise

Example 10: Logging exceptions

import logging
try:
  1 / 0
except ZeroDivisionError as e:
  logging.error("Exception occurred", exc_info=True)