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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
# /// script
|
2 |
+
# requires-python = ">=3.10"
|
3 |
+
# dependencies = [
|
4 |
+
# "marimo",
|
5 |
+
# ]
|
6 |
+
# ///
|
7 |
+
|
8 |
+
import marimo
|
9 |
+
|
10 |
+
__generated_with = "0.10.16"
|
11 |
+
app = marimo.App()
|
12 |
+
|
13 |
+
|
14 |
+
@app.cell
|
15 |
+
def _():
|
16 |
+
import marimo as mo
|
17 |
+
return (mo,)
|
18 |
+
|
19 |
+
|
20 |
+
@app.cell(hide_code=True)
|
21 |
+
def _(mo):
|
22 |
+
mo.md(
|
23 |
+
"""
|
24 |
+
# π‘οΈ Error Management in Python
|
25 |
+
|
26 |
+
Welcome to the world of Python error handling - where bugs become learning opportunities!
|
27 |
+
|
28 |
+
## Why Error Handling Matters
|
29 |
+
Imagine your code as a superhero navigating through the treacherous landscape of potential problems.
|
30 |
+
Error handling is like your hero's shield, protecting your program from unexpected challenges.
|
31 |
+
|
32 |
+
```python
|
33 |
+
# Without error handling
|
34 |
+
result = 10 / 0 # π₯ Boom! Unhandled ZeroDivisionError
|
35 |
+
|
36 |
+
# With error handling
|
37 |
+
try:
|
38 |
+
result = 10 / 0
|
39 |
+
except ZeroDivisionError:
|
40 |
+
result = "Oops! Can't divide by zero π"
|
41 |
+
```
|
42 |
+
"""
|
43 |
+
)
|
44 |
+
return
|
45 |
+
|
46 |
+
|
47 |
+
@app.cell
|
48 |
+
def _(error_types):
|
49 |
+
error_types
|
50 |
+
return
|
51 |
+
|
52 |
+
|
53 |
+
@app.cell(hide_code=True)
|
54 |
+
def _(mo):
|
55 |
+
# Choose error type
|
56 |
+
error_types = mo.ui.dropdown(
|
57 |
+
options=[
|
58 |
+
"ZeroDivisionError",
|
59 |
+
"TypeError",
|
60 |
+
"ValueError",
|
61 |
+
"IndexError",
|
62 |
+
"KeyError"
|
63 |
+
],
|
64 |
+
label="Select an Error Type to Explore"
|
65 |
+
)
|
66 |
+
return (error_types,)
|
67 |
+
|
68 |
+
|
69 |
+
@app.cell(hide_code=True)
|
70 |
+
def _(error_types, mo):
|
71 |
+
# Error explanation
|
72 |
+
error_explanations = {
|
73 |
+
"ZeroDivisionError": """
|
74 |
+
### π« ZeroDivisionError
|
75 |
+
- Occurs when you try to divide by zero
|
76 |
+
- Mathematical impossibility
|
77 |
+
- Example:
|
78 |
+
```python
|
79 |
+
x = 10 / 0 # Triggers ZeroDivisionError
|
80 |
+
```
|
81 |
+
""",
|
82 |
+
"TypeError": """
|
83 |
+
### π TypeError
|
84 |
+
- Happens when an operation is applied to an inappropriate type
|
85 |
+
- Mixing incompatible types
|
86 |
+
- Example:
|
87 |
+
```python
|
88 |
+
"2" + 3 # Can't add string and integer
|
89 |
+
```
|
90 |
+
""",
|
91 |
+
"ValueError": """
|
92 |
+
### π ValueError
|
93 |
+
- Raised when a function receives an argument of correct type
|
94 |
+
but inappropriate value
|
95 |
+
- Example:
|
96 |
+
```python
|
97 |
+
int("hello") # Can't convert non-numeric string to int
|
98 |
+
```
|
99 |
+
""",
|
100 |
+
"IndexError": """
|
101 |
+
### π IndexError
|
102 |
+
- Occurs when trying to access a list index that doesn't exist
|
103 |
+
- Going beyond list boundaries
|
104 |
+
- Example:
|
105 |
+
```python
|
106 |
+
my_list = [1, 2, 3]
|
107 |
+
print(my_list[5]) # Only has indices 0, 1, 2
|
108 |
+
```
|
109 |
+
""",
|
110 |
+
"KeyError": """
|
111 |
+
### ποΈ KeyError
|
112 |
+
- Raised when trying to access a dictionary key that doesn't exist
|
113 |
+
- Example:
|
114 |
+
```python
|
115 |
+
my_dict = {"a": 1, "b": 2}
|
116 |
+
print(my_dict["c"]) # "c" key doesn't exist
|
117 |
+
```
|
118 |
+
"""
|
119 |
+
}
|
120 |
+
|
121 |
+
mo.md(error_explanations.get(error_types.value, "Select an error type"))
|
122 |
+
return (error_explanations,)
|
123 |
+
|
124 |
+
|
125 |
+
@app.cell
|
126 |
+
def _(division_input, divisor_input, mo):
|
127 |
+
mo.hstack([division_input, divisor_input])
|
128 |
+
return
|
129 |
+
|
130 |
+
|
131 |
+
@app.cell(hide_code=True)
|
132 |
+
def _(mo):
|
133 |
+
# Try-Except work help
|
134 |
+
division_input = mo.ui.number(
|
135 |
+
value=10,
|
136 |
+
label="Number to Divide",
|
137 |
+
start=-100,
|
138 |
+
stop=100
|
139 |
+
)
|
140 |
+
divisor_input = mo.ui.number(
|
141 |
+
value=0,
|
142 |
+
label="Divisor",
|
143 |
+
start=-100,
|
144 |
+
stop=100
|
145 |
+
)
|
146 |
+
return division_input, divisor_input
|
147 |
+
|
148 |
+
|
149 |
+
@app.cell
|
150 |
+
def _(division_input, divisor_input, mo):
|
151 |
+
# Safe division function with appropriate error handling
|
152 |
+
def safe_divide(numerator, denominator):
|
153 |
+
try:
|
154 |
+
_result = numerator / denominator
|
155 |
+
return f"Result: {_result}"
|
156 |
+
except ZeroDivisionError:
|
157 |
+
return "π« Cannot divide by zero!"
|
158 |
+
except Exception as e:
|
159 |
+
return f"Unexpected error: {e}"
|
160 |
+
|
161 |
+
# Display result with explanation
|
162 |
+
_result = safe_divide(division_input.value, divisor_input.value)
|
163 |
+
|
164 |
+
mo.hstack([
|
165 |
+
mo.md(f"**Division**: {division_input.value} Γ· {divisor_input.value}"),
|
166 |
+
mo.md(f"**Result**: {_result}")
|
167 |
+
])
|
168 |
+
return (safe_divide,)
|
169 |
+
|
170 |
+
|
171 |
+
@app.cell
|
172 |
+
def _(mo):
|
173 |
+
# Multiple Exception Handling
|
174 |
+
mo.md(
|
175 |
+
"""
|
176 |
+
## Multiple Exception Handling
|
177 |
+
Catch and handle different types of errors specifically:
|
178 |
+
|
179 |
+
```python
|
180 |
+
def complex_function(x, y):
|
181 |
+
try:
|
182 |
+
# Potential errors: TypeError, ZeroDivisionError
|
183 |
+
result = x / y
|
184 |
+
return int(result)
|
185 |
+
except TypeError:
|
186 |
+
return "Type mismatch!"
|
187 |
+
except ZeroDivisionError:
|
188 |
+
return "No division by zero!"
|
189 |
+
except ValueError:
|
190 |
+
return "Conversion error!"
|
191 |
+
```
|
192 |
+
"""
|
193 |
+
)
|
194 |
+
return
|
195 |
+
|
196 |
+
|
197 |
+
@app.cell
|
198 |
+
def _(error_chain_input):
|
199 |
+
error_chain_input
|
200 |
+
return
|
201 |
+
|
202 |
+
|
203 |
+
@app.cell
|
204 |
+
def _(mo):
|
205 |
+
# Try it out
|
206 |
+
error_chain_input = mo.ui.text(
|
207 |
+
label="Try to break the code",
|
208 |
+
placeholder="Enter something tricky..."
|
209 |
+
)
|
210 |
+
return (error_chain_input,)
|
211 |
+
|
212 |
+
|
213 |
+
@app.cell
|
214 |
+
def _(error_chain_input, mo):
|
215 |
+
# Error chain demonstration
|
216 |
+
def tricky_function(input_str):
|
217 |
+
try:
|
218 |
+
# Simulating a error scenario
|
219 |
+
number = int(input_str)
|
220 |
+
result = 100 / number
|
221 |
+
return f"Success! Result: {result}"
|
222 |
+
except ValueError:
|
223 |
+
return "β Could not convert to number"
|
224 |
+
except ZeroDivisionError:
|
225 |
+
return "β Cannot divide by zero"
|
226 |
+
except Exception as e:
|
227 |
+
return f"π€― Unexpected error: {type(e).__name__}"
|
228 |
+
|
229 |
+
result = tricky_function(error_chain_input.value)
|
230 |
+
|
231 |
+
mo.hstack([
|
232 |
+
mo.md(f"**Input**: {error_chain_input.value}"),
|
233 |
+
mo.md(f"**Result**: {result}")
|
234 |
+
])
|
235 |
+
return result, tricky_function
|
236 |
+
|
237 |
+
|
238 |
+
@app.cell
|
239 |
+
def _(finally_input):
|
240 |
+
finally_input
|
241 |
+
return
|
242 |
+
|
243 |
+
|
244 |
+
@app.cell
|
245 |
+
def _(mo):
|
246 |
+
# Finally Block Demonstration
|
247 |
+
finally_input = mo.ui.switch(
|
248 |
+
label="Simulate Resource Management",
|
249 |
+
value=True
|
250 |
+
)
|
251 |
+
return (finally_input,)
|
252 |
+
|
253 |
+
|
254 |
+
@app.cell
|
255 |
+
def _(finally_input, mo):
|
256 |
+
def simulate_resource_management():
|
257 |
+
try:
|
258 |
+
# Simulating a resource-intensive operation
|
259 |
+
if finally_input.value:
|
260 |
+
return "π’ Resource processing successful"
|
261 |
+
else:
|
262 |
+
raise Exception("Simulated failure")
|
263 |
+
except Exception as e:
|
264 |
+
return f"π΄ Error: {e}"
|
265 |
+
finally:
|
266 |
+
return "π¦ Resource cleanup completed"
|
267 |
+
|
268 |
+
_result = simulate_resource_management()
|
269 |
+
|
270 |
+
mo.md(f"""
|
271 |
+
### Resource Management Simulation
|
272 |
+
|
273 |
+
**Scenario**: {'Normal operation' if finally_input.value else 'Error scenario'}
|
274 |
+
|
275 |
+
**Result**: {_result}
|
276 |
+
|
277 |
+
Notice how the `finally` block always runs, ensuring cleanup!
|
278 |
+
""")
|
279 |
+
return (simulate_resource_management,)
|
280 |
+
|
281 |
+
|
282 |
+
@app.cell(hide_code=True)
|
283 |
+
def _(mo):
|
284 |
+
callout_text = mo.md("""
|
285 |
+
## Your Error Handling Journey Continues!
|
286 |
+
|
287 |
+
Next Steps:
|
288 |
+
|
289 |
+
- Practice creating custom exceptions
|
290 |
+
- Explore context managers
|
291 |
+
- Build robust error-handling strategies
|
292 |
+
|
293 |
+
You're becoming a Python error-handling ninja! π₯·π
|
294 |
+
""")
|
295 |
+
|
296 |
+
mo.callout(callout_text, kind="success")
|
297 |
+
return (callout_text,)
|
298 |
+
|
299 |
+
|
300 |
+
if __name__ == "__main__":
|
301 |
+
app.run()
|