๐Ÿ Lesson 23: Python Exception Handling – Try, Except & Custom Errors

Welcome to Lesson 23! Today we’ll explore exception handling in Python. Exceptions are errors that occur during program execution, and handling them ensures your program doesn’t crash unexpectedly. Mastering exception handling will make your programs more robust and user-friendly.


⭐ What You Will Learn in This Lesson

  • How to use try and except to handle errors
  • Manage multiple exceptions and prevent program crashes
  • Use else and finally to enhance exception handling
  • How to raise custom exceptions for better error handling

๐Ÿ‘ฅ Who Is This Lesson For?

  • Python developers who want to improve error handling in their code
  • Anyone building robust applications that require user input validation
  • Developers interested in making their code more fault-tolerant and user-friendly

๐Ÿ“ฆ 1. Basic Try & Except

Start by handling simple errors using try and except:


try:
    num = int(input("Enter a number: "))
    print("You entered:", num)
except ValueError:
    print("Oops! That’s not a valid number.")

๐Ÿ“ฆ 2. Handling Multiple Exceptions

You can handle multiple exceptions by chaining except blocks:


try:
    x = 10 / 0
except ZeroDivisionError:
    print("Cannot divide by zero!")
except ValueError:
    print("Invalid value!")

๐Ÿ“ฆ 3. Using Else & Finally

else runs if no exception occurs, while finally always runs regardless of errors:


try:
    num = int(input("Enter a number: "))
except ValueError:
    print("Invalid input!")
else:
    print("Success! You entered:", num)
finally:
    print("This always runs.")

๐Ÿ“ฆ 4. Raising Exceptions

You can raise custom exceptions with the raise statement:


age = -5
if age < 0:
    raise ValueError("Age cannot be negative!")

๐Ÿ“ฆ 5. Custom Exception Classes

For more control, create custom exception classes to handle specific errors:


class NegativeAgeError(Exception):
    pass

age = -10
try:
    if age < 0:
        raise NegativeAgeError("Age cannot be negative!")
except NegativeAgeError as e:
    print("Error:", e)

๐Ÿงฉ 6. Why Exception Handling Matters

  • Prevents program crashes
  • Helps debug and log errors
  • Makes code robust and user-friendly
  • Essential for real-world applications and APIs

๐Ÿงช Practice

  1. Write a program that divides two numbers and handles division by zero.
  2. Prompt for an integer input and handle invalid entries.
  3. Create a custom exception for invalid email format and raise it.
  4. Use finally to print a goodbye message in a program.

❌ Common Mistakes

  • Not catching the correct exception
  • Forgetting to raise custom exceptions when necessary
  • Misusing the else and finally blocks

❓ Frequently Asked Questions (FAQ)

1. What is the difference between except and finally?

except handles errors, while finally ensures that the code in it will always run, regardless of whether an exception occurs or not.

2. Why should I use custom exceptions?

Custom exceptions provide more meaningful error messages and allow you to handle specific errors more effectively.

3. Can I use else without finally?

Yes! The else block can be used without finally. It runs only if no exceptions were raised in the try block.


๐Ÿš€ What’s Next?

In the next lesson, you’ll learn about:

  • Context Managers and how to manage resources like files and connections
  • Understanding the with statement for resource management
  • How to write cleaner code with automatic cleanup

➡ Next Lesson

Go to Lesson 24 →

Comments

Popular posts from this blog

How to Install Geany 2.1 on Windows 10/11 (2026) | Step-by-Step Guide

How to Uninstall Bluefish 2.2.19 on Windows 10/11 (2026) | Step-by-Step Guide

How to Install Visual Studio 2026 on Windows 10/11 | Step-by-Step Guide