[concept]String & File Ops
Error Handling
# theory
try/except
Catch errors and handle them gracefully:
try:
result = 10 / 0
except ZeroDivisionError:
print("Cannot divide by zero!")
common exception types
| Exception | When it occurs |
|---|---|
| ValueError | Wrong value (e.g., int("abc")) |
| KeyError | Dict key doesn't exist |
| IndexError | List index out of range |
| FileNotFoundError | File doesn't exist |
| TypeError | Wrong type for operation |
| ZeroDivisionError | Division by zero |
multiple exceptions
try:
# risky code
value = int(user_input)
result = data[value]
except ValueError:
print("Not a valid number")
except KeyError:
print("Key not found")
except (IndexError, TypeError) as e:
print(f"Error: {e}")
else and finally
try:
file = open("data.txt")
except FileNotFoundError:
print("File not found")
else:
# Runs only if no exception
content = file.read()
file.close()
finally:
# Always runs
print("Done")
raising
def divide(a, b):
if b == 0:
raise ValueError("Cannot divide by zero")
return a / b# examples [3]
# example 01 · safe type conversion
Handle invalid input gracefully
1
2
3
4
5
6
7
8
9
10
🐍
# example 02 · dictionary access with default
Handle missing keys gracefully
1
2
3
4
5
6
7
8
9
10
11
12
13
14
🐍
# example 03 · processing with error handling
Continue processing even when some items fail
1
2
3
4
5
6
7
8
9
10
11
12
🐍
# challenges [2]
# challenge 01/02todo
Write a function safe_get(lst, index) that returns the item at index, or 'Not found' if index is out of range.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
🐍
# challenge 02/02todo
Convert ['1', '2', 'x', '4'] to integers, skipping invalid values. Print the sum of valid numbers.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
🐍
# project
# project-challenge
thread: Sales Performance Dashboard · reward: 50 xp
# brief
Some sales records might have invalid data. Create a function that safely calculates revenue, handling cases where Quantity or UnitPrice might be invalid, and returns 0 for those records.
# task
Safe Revenue Calculator
# your code
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
🐍