File tree 5 files changed +72
-0
lines changed
5 files changed +72
-0
lines changed Original file line number Diff line number Diff line change
1
+ # Day 9: Error Handling
2
+
3
+ ## What You'll Learn:
4
+ - Handling exceptions with ` try/except `
5
+ - Using ` finally ` for cleanup operations
6
+ - Raising custom exceptions
7
+ - Built-in exception types
8
+
9
+ ## Files:
10
+ 1 . ` basic_try_except.py ` - Simple error catching
11
+ 2 . ` specific_exceptions.py ` - Handling different error types
12
+ 3 . ` finally_usage.py ` - Cleanup operations
13
+ 4 . ` raising_exceptions.py ` - Custom error raising
14
+
15
+ ## Exercises:
16
+ 1 . Create a number input validator that:
17
+ - Keeps asking for input until valid number
18
+ - Handles both ValueError and KeyboardInterrupt
19
+ - Prints "Thank you!" on successful input
20
+
21
+ 2 . Build a file reader that:
22
+ - Gracefully handles missing files
23
+ - Shows different messages for different error types
24
+ - Always closes file resources
Original file line number Diff line number Diff line change
1
+ # Basic error handling
2
+ try :
3
+ result = 10 / 0
4
+ except ZeroDivisionError :
5
+ print ("Cannot divide by zero!" )
6
+
7
+ # Generic exception
8
+ try :
9
+ print (undefined_variable )
10
+ except Exception as e :
11
+ print (f"Error occurred: { str (e )} " )
Original file line number Diff line number Diff line change
1
+ # Finally block example
2
+ try :
3
+ file = open ("data.txt" , "r" )
4
+ content = file .read ()
5
+ print (content )
6
+ except FileNotFoundError :
7
+ print ("File doesn't exist" )
8
+ finally :
9
+ file .close () if 'file' in locals () else None
10
+ print ("Cleanup complete" )
Original file line number Diff line number Diff line change
1
+ # Raising exceptions
2
+ def validate_age (age ):
3
+ if age < 0 :
4
+ raise ValueError ("Age cannot be negative" )
5
+ if age > 120 :
6
+ raise ValueError ("Unrealistic age" )
7
+
8
+ try :
9
+ validate_age (- 5 )
10
+ except ValueError as e :
11
+ print (f"Invalid age: { e } " )
12
+
13
+ # Custom exception
14
+ class InvalidEmailError (Exception ):
15
+ pass
16
+
17
+ def validate_email (email ):
18
+ if "@" not in email :
19
+ raise InvalidEmailError ("Missing @ symbol" )
Original file line number Diff line number Diff line change
1
+ # Handling specific exceptions
2
+ try :
3
+ file = open ("missing.txt" , "r" )
4
+ value = int ("abc" )
5
+ except FileNotFoundError :
6
+ print ("File not found!" )
7
+ except ValueError :
8
+ print ("Invalid conversion to integer" )
You can’t perform that action at this time.
0 commit comments