Keyboard Shortcuts N Next post
P Previous post
S Save / unsave
R Read aloud
T Toggle theme
/ Focus search
Esc Close panels
🔥
Ready to read...
errors Module 6 - File Handling & Errors Python Python Basics Python Programming: From Zero to Real-World Applications

Exception Handling - try, except, finally in Python

Reviewed & accurate
AI Summary

What You Will Learn

Beginner

  • How try/except/finally works
  • Catching specific exceptions
  • Raising your own exceptions
Terminalpython
try:
    num = int(input("Enter a number: "))
    result = 10 / num
    print(f"10 / {num} = {result}")
except ValueError:
    print("That is not a valid number!")
except ZeroDivisionError:
    print("Cannot divide by zero!")
except Exception as e:
    print(f"An unexpected error: {e}")
else:
    print("No errors occurred.")
finally:
    print("This always runs, error or not.")

Common Exceptions

ExceptionWhen
ValueErrorWrong value type (int("hello"))
TypeErrorWrong type ("a" + 1)
ZeroDivisionErrorDivision by zero
IndexErrorList index out of range
KeyErrorDictionary key not found
FileNotFoundErrorFile does not exist
Never use bare except
except: without a specific type catches EVERYTHING - including Ctrl+C and SystemExit. Always catch specific exceptions: except ValueError, except FileNotFoundError.

Practical Exercise

Wrap int(input()) in try/except ValueError
Handle ZeroDivisionError for 10 / 0
Use else for success code, finally for cleanup
Raise an exception: raise ValueError("Bad input")

Key Takeaways

  • try: code that might fail.
  • except SpecificError: handle specific errors.
  • else: runs if no exception. finally: always runs.
  • Never use bare except - always specify the exception type.
  • raise ExceptionType("message") to throw your own.
Previously: Lesson 38 covered CSV.
Today: You learned: Handle errors gracefully with try/except.
Next: Lesson 40 covers custom exceptions.
Test Your Knowledge
How did you find this?

Comments

Join the discussion! Sign in with your Google or Blogger account, or comment as Anonymous - no account needed. For quick questions, also reach me on Telegram @cytestch.

Comments