Back to Blog

Exception Handling (try, except, raise, finally, custom exceptions) - Python Tutorial #16

Sandy LaneSandy Lane

Video: Exception Handling (try, except, raise, finally, custom exceptions) - Python Tutorial #16 by Taught by Celeste AI - AI Coding Coach

Watch full page →

Exception Handling in Python: try, except, raise, finally, and Custom Exceptions

Handling errors gracefully is essential in Python programming to prevent crashes and provide meaningful feedback. This tutorial covers how to use try and except blocks to catch errors, raise exceptions intentionally, and define custom exception classes for more precise error management.

Code

# Basic try/except to catch errors
try:
  num = int(input("Enter a number: "))
  result = 10 / num
except ValueError:
  print("That's not a valid integer!")
except ZeroDivisionError:
  print("Cannot divide by zero!")
else:
  print(f"Result is {result}")
finally:
  print("Execution of try-except block is complete.")

# Raising an exception intentionally
def check_age(age):
  if age < 0:
    raise ValueError("Age cannot be negative")
  print(f"Age is {age}")

try:
  check_age(-5)
except ValueError as e:
  print(f"Error: {e}")

# Custom exception class
class InputTooShortError(Exception):
  pass

def validate_username(username):
  if len(username) < 5:
    raise InputTooShortError("Username must be at least 5 characters long")
  print("Username is valid")

try:
  validate_username("abc")
except InputTooShortError as e:
  print(f"Validation error: {e}")

Key Points

  • try blocks let you test code that might raise exceptions, while except blocks catch and handle those exceptions.
  • You can catch specific exceptions like ValueError or ZeroDivisionError to handle different error types distinctly.
  • The else clause runs if no exceptions occur, and finally always runs regardless of errors.
  • Use raise to throw exceptions intentionally when detecting invalid conditions.
  • Custom exception classes let you define meaningful error types tailored to your application's needs.