Error handling is an important part of programming. Without it, your program will stop running whenever it encounters an error. Python provides the
try and except blocks to gracefully handle errors and keep your program running.
πΉ Why Use try and except?
Imagine you ask a user to enter a number, but they type text instead. Without error handling, your program will crash.
With try and except, you can catch the error and show a friendly message instead.
πΉ Syntax of try and except
try:
# Code that might cause an error
risky_code
except:
# Code to run if an error occurs
handle_error
✅ The try block runs first.
✅ If no error occurs, the except block is skipped.
✅ If an error occurs, the program jumps directly to the except block.
πΉ Example
try:
number = int(input("Enter a number: "))
print("You entered:", number)
except:
print("Oops! That was not a valid number.")
π If the user types 10, it prints: You entered: 10.
π If the user types hello, it prints: Oops! That was not a valid number.
⚠️ Common Mistakes
- Forgetting indentation → Python will throw
IndentationError. - Using capitalized
TryorExcept→ Python keywords are lowercase only. - Using a too-general except block → Always try to catch specific errors when possible.
No comments:
Post a Comment