Catching Multiple Exceptions in Python

In Python, a block of code inside a try statement can raise different types of errors (exceptions). To handle each one appropriately, you can catch them separately or group them together, depending on your use case.

Method 1: Multiple except Blocks

Syntax:

try:
   # Code that might raise multiple exceptions
except FirstException:
   # Handle FirstException
except SecondException:
   # Handle SecondException

Example:

try:
   x = int("abc")      # Will raise ValueError
   y = 10 / 0          # Will raise ZeroDivisionError (never reached)
except ValueError:
   print("ValueError: Invalid input")
except ZeroDivisionError:
   print("ZeroDivisionError: Division by zero")

Output:

ValueError: Invalid input

Explanation:

  • This approach catches different exceptions in separate blocks.
  • Only the first error is handled (ValueError in this case), and the rest are skipped.
  • This is useful when each exception needs different handling logic.

Method 2: Catching Multiple Exceptions in One Block

Syntax:

try:
   # Risky code
except (ExceptionType1, ExceptionType2) as e:
   # Handle both exceptions

Example:

try:
   x = int("abc")
   y = 10 / 0
except (ValueError, ZeroDivisionError) as e:
   print("An error occurred:", e)

Output:

An error occurred: invalid literal for int() with base 10: 'abc'

Explanation:

  • You can use a tuple to catch multiple exceptions in a single block.
  • The variable e will store the actual error object.
  • This is cleaner when different exceptions need the same response.

Method 3: Catching All Exceptions (Generic Catch)

Syntax:

try:
   # Some risky code
except Exception as e:
   print("Error:", e)

Example:

try:
   x = int("abc")
except Exception as e:
   print("Caught an exception:", e)

Output:

Caught an exception: invalid literal for int() with base 10: 'abc'

Explanation:

  • This catches any exception that inherits from the base Exception class.
  • Not recommended for general use because it can hide bugs or unexpected errors.
  • Useful when logging errors or during debugging.

Best Practices

TipExplanation
✅ Be specificCatch only the exceptions you expect
✅ Use exception namesHelps understand what went wrong
❌ Avoid except: aloneIt catches everything, including system-exiting exceptions
✅ Use as eLets you inspect or log the error