Exception Handling in Python: Complete Guide with Examples

Nothing kills a smooth-running Python script faster than a nasty exception crashing your program midrun. And yet, exceptions show up all the time errors in input, server issues, invalid operations. That’s why exception handling is a must-know skill. Ready to make your code rock-solid? Let’s dive in.

Exception Handling in Python

1. Why Handle Exceptions? 

Imagine you’re building a calculator app. Someone enters / boom, ZeroDivisionError and your entire app crashes. Ouch. 

Exception handling helps you: 

  • Catch errors before they crash your app 
  • Provide meaningful feedback to users 
  • Keep your program running smoothly 

 

2. Basic Exception Handling with Try–Except 

try: 

Copy Code

x = int(input("Enter a number: ")) 

    y = int(input("Enter another: ")) 

    print("Result:", x / y) 

except ZeroDivisionError: 

    print(" Cannot divide by zero!")

Output Example: 

Enter a number: 10 

Enter another: 0 

Cannot divide by zero! 

Simple and clean. Your code inside try runs; if an exception occurs, it jumps to the matching except block. 

3. Catching Multiple Exceptions 

Copy Code

try: 

    x = int(input("Enter a number: ")) 

    y = int(input("Enter another: ")) 

    print("Result:", x / y) 

except ValueError: 

    print("Please enter integers only.") 

except ZeroDivisionError: 

    print("Cannot divide by zero.")

Output Examples: 

Enter a number: a 

Please enter integers only. 

Powerful way to handle diverse errors distinctly. 

4. Using else and finally 

Copy Code

try: 

    f = open("data.txt") 

    data = f.read() 

except FileNotFoundError: 

    print("Sorry, file not found.") 

else: 

    print("File content:", data) 

finally: 

    print("Closing file.") 

    try: 

        f.close() 

    except: 

        pass
  • else runs only if try is successful 
  • finally always runs great for cleanup (e.g. close files, network connections) 

5. Raising Custom Exceptions 

Sometimes you want to raise your own errors: 

Copy Code

def get_age(): 

    age = int(input("Age: ")) 

    if age < 0: 

        raise ValueError("Age can’t be negative!") 

    return age 

try: 

    print(get_age()) 

except ValueError as ve: 

    print("Error:", ve)

Creates meaningful, contextspecific exceptions. 

6. Catching All Exceptions (Use With Care) 

Copy Code

try: 

    risky_code() 

except Exception as e: 

    print("Something went wrong:", e)

Be specific when possible catching all exceptions can hide bugs. But it's useful for top-level logging or cleanup. 

7. Example: Robust Calculator with Error Handling 

Copy Code

def get_num(prompt): 

    while True: 

        try: 

            return int(input(prompt)) 

        except ValueError: 

            print("That’s not a valid number try again.") 

x = get_num("Enter num1: ") 

y = get_num("Enter num2: ") 

try: 

    choice = input("Choose (+, -, *, /): ") 

    if choice == "+": 

        result = x + y 

    elif choice == "-": 

        result = x - y 

    elif choice == "*": 

        result = x * y 

    elif choice == "/": 

        result = x / y 

    else: 

        raise ValueError("Invalid operation!") 

    print("Result:", result) 

except ValueError as ve: 

    print("Error:", ve) 

except ZeroDivisionError: 

    print("Cannot divide by zero.")

Handles input errors, invalid choices, division by zero all smooth and user-friendly. 

8. Best Practices for Exception Handling 

  • Be specific in your except blocks 
  • Avoid bare except:; use except Exception: if truly needed 
  • Use else for code that runs when no exceptions occur 
  • Use finally or context managers (with open(...)) for cleanup 

9. Learn More with Uncodemy 

Want to master exception handling and other Python essentials? Check out Uncodemy’s Python Programming Course. They offer hands-on projects, real-world examples, and clear explanations to help you code smarter and cleaner. 

FAQs 

1. What’s the difference between Exception and BaseException? 
BaseException is the superclass of all exceptions, including system-level ones like SystemExit. Stick with Exception in most cases. 

2. Can I use try…finally without except? 
Yes. Just use it if you always want cleanup like releasing resources even without error handling. 

3. Is it bad to catch multiple exceptions in one go? 
It’s okay if you handle them similarly. Eg. except (ValueError, TypeError):. 

4. Will finally run if I return inside try? 
Yes. finally always executes even on return, break, or sys.exit(). 

5. Should I use exceptions for control flow? 
Not really. Use exceptions for exceptional cases not as normal logic. 

Final Thoughts 

Exception handling isn’t just a coding safeguard it lets your script communicate gracefully, recover intelligently, and prevent awkward crashes. 
Once you apply these patterns, your Python code will feel more professional, robust, and ready for real-world use. 

 

Placed Students

Our Clients

Partners

...

Uncodemy Learning Platform

Uncodemy Free Premium Features

Popular Courses