Lesson 12: Exception Handling in Python

🎯 Lesson Objective

To understand how to handle errors in Python gracefully using exceptions, preventing program crashes and improving reliability.


🧩 1. What Is an Exception?

An exception is an error that occurs during program execution.
Examples: dividing by zero, file not found, invalid input, etc.

βœ… Example:

num = 10
print(num / 0)  # This will raise ZeroDivisionError

Output:

ZeroDivisionError: division by zero

βš™οΈ 2. Try and Except Block

Use try to test code and except to handle exceptions.

try:
    num = int(input("Enter a number: "))
    print(10 / num)
except ZeroDivisionError:
    print("Cannot divide by zero!")
except ValueError:
    print("Invalid input! Enter an integer.")

Behavior:

  • If input is 0 β†’ prints “Cannot divide by zero!”
  • If input is not a number β†’ prints “Invalid input! Enter an integer.”

πŸ”„ 3. Handling Multiple Exceptions

You can handle multiple exceptions in one block.

try:
    x = int(input("Enter a number: "))
    y = int(input("Enter another number: "))
    result = x / y
except (ZeroDivisionError, ValueError) as e:
    print("Error occurred:", e)
else:
    print("Result is:", result)
finally:
    print("Execution finished.")

🧰 4. Common Built-in Exceptions

ExceptionCauseExample
ZeroDivisionErrorDivision by zero10/0
ValueErrorInvalid valueint("abc")
FileNotFoundErrorFile doesn’t existopen("nofile.txt")
TypeErrorWrong data type"5" + 5
IndexErrorInvalid indexarr[10]
KeyErrorKey not found in dictdict["x"]

πŸ” 5. Try, Except, Else, Finally

try:
    num = int(input("Enter a number: "))
    result = 10 / num
except ZeroDivisionError:
    print("Cannot divide by zero!")
else:
    print("Division successful, result:", result)
finally:
    print("End of program")
  • try: code that may raise an exception
  • except: code to handle exception
  • else: runs if no exception occurs
  • finally: always runs

🧩 6. Raising Exceptions

You can raise exceptions intentionally using raise.

age = int(input("Enter your age: "))
if age < 18:
    raise ValueError("Age must be 18 or above.")

🌍 7. Real-Life Example – Safe Input


while True:
    try:
        num = int(input("Enter a positive number: "))
        if num < 0:
            raise ValueError("Number cannot be negative")
        break
    except ValueError as e:
        print("Error:", e)

print("You entered:", num)

Comments

Leave a Reply

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