Python Exception Handling

Exceptions are errors that occur while running a program. Instead of stopping the program suddenly, Python allows us to handle these errors safely. Exception handling makes programs more reliable and user-friendly.
Example: If you try to divide a number by zero, Python will raise an exception.

Try and Except Block

When you suspect a specific block of code might cause an error (like dividing by zero or opening a non-existent file), you don’t run it blindly. Instead, you wrap it in a “safety net”. You “try” to run the code, and if it fails, the “except” block catches the error and executes a backup plan. This prevents the entire program from stopping abruptly and allows you to show a friendly error message to the user instead of a scary technical report.

# We try to access an item in a list that doesn't exist
cart_items = ["Apple", "Banana"]

try:
  # Trying to pick the 10th item (which is impossible)
  print(cart_items[10])

except:
  # This runs only if the code above crashes
  print("Oops! That item is not in your cart.")

Multiple Except Blocks

We can use different except blocks to handle different types of errors separately.
user_input = "Five"

try:
  # Trying to do math with a word instead of a number
  result = 100 / int(user_input)
except ValueError:
  # This specifically catches conversion errors (Text to Number)
  print("Please enter a digit like 5, not a word.")
except ZeroDivisionError:
  # This specifically catches division by zero
  print("You cannot divide by zero!")

Else Block in Exception Handling

The else block runs only if no error occurs inside the try block. It is useful for code that should run when everything is fine.
try:
  number = int("50")  # This conversion works fine
except ValueError:
  print("That is not a valid number.")
else:
  # This runs because the conversion was successful
  print(f"Success! We recorded your number: {number}")

Finally Block

The finally block is used to run code no matter what happens. It is often used to close files or release resources.
try:
  print("Opening the database connection...")
  # Imagine we are doing some work here
  result = 10 / 0  # This causes a crash!
except ZeroDivisionError:
  print("Error: Calculation failed.")
finally:
  # This runs even though the crash happened above
  print("Closing the database connection safely.")

Raising Exceptions

Sometimes, Python’s standard errors aren’t enough. You might want to stop the program if a business rule is violated, even if the code is technically correct. The raise keyword allows you to trigger an error manually.
age = -5

if age < 0:
  # We manually trigger an error because negative age is impossible
  raise ValueError("Age cannot be negative!")
else:
  print(f"Your age is {age}")
Post a comment

Leave a Comment

Your email address will not be published. Required fields are marked *

Scroll to Top