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
| Exception | When |
|---|---|
ValueError | Wrong value type (int("hello")) |
TypeError | Wrong type ("a" + 1) |
ZeroDivisionError | Division by zero |
IndexError | List index out of range |
KeyError | Dictionary key not found |
FileNotFoundError | File 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.
Comments
Comments
Post a Comment