
![]() |
@wtf | |
(Build a safe input reader) |
||
1
Replies
18
Views
1 Bookmarks
|
![]() |
@wtf | 25 June 25 |
*Error Handling in Python* When something unexpected happens — like dividing by zero or reading a missing file — Python raises an exception. If not handled, your program crashes. *The try...except Block* try: risky code except SomeError: handle error *Example* : try: x = int(input(Enter a number: )) print(10 / x) except ZeroDivisionError: print(You can't divide by zero!) except ValueError: print(Please enter a valid number.) *else and finally* else: runs if no exception was raised finally: runs no matter what (cleanup code) try: num = int(input(Enter number: )) except ValueError: print(Not a number!) else: print(Square is, num ** 2) finally: print(Done.) *Common Exceptions:* - ZeroDivisionError – dividing by zero - ValueError – invalid value (e.g., int(abc)) - TypeError – wrong data type - FileNotFoundError – file doesn't exist - IndexError – index out of range *Mini Project: Safe Input Reader* A safe input reader is a function or piece of code that asks the user for input — but doesn’t crash if the user types something invalid. *Python Code*: def get_integer(prompt): try: return int(input(prompt)) except ValueError: print(That's not a valid integer!) return None num = None while num is None: num = get_integer(Enter an integer: ) print(You entered:, num) *This project helps:* - Prevent program crashes - Give user-friendly error messages - Build real-world safety into your code |
||


