Exceptions · ข้อยกเว้น (Exceptions)
When things go wrong
- A runtime error normally crashes the program.
- An exception is Python's signal that something went wrong.
- Exception handling lets you catch it and keep running.
try / except
- Put risky code in a
try:block. - If it raises an exception, the
except:block runs instead of crashing. - If nothing goes wrong, the
exceptblock is skipped.
try:
number = int("not a number")
except ValueError:
number = 0
print(number)
Catch the right error
- Name the type of error you expect:
except ValueError:. ValueErroris bad text for a number;ZeroDivisionErroris divide by zero.- Catching a specific type means you do not hide other bugs.
try:
print(10 / 0)
except ZeroDivisionError:
print("Cannot divide by zero")
finally and raise
- A
finally:block always runs, error or not — good for cleanup. raiselets you signal an error on purpose.raise ValueError("message")stops the code unless something catches it.
try:
raise ValueError("bad value")
except ValueError as e:
print("Caught:", e)
finally:
print("Always runs")
Why it matters
- A robust program should not crash on bad input.
- Handling exceptions lets it warn the user and carry on.
- It also makes sure files and other resources are closed cleanly.
Common mistakes
- Catch a specific error (
except ValueError:), not a bareexcept:. - Put only the risky line inside the
try.
Now you try
- Use
try/except(andraisein the last task). - Press Check answer to test your code.
try / except
Code runs in try; if it fails, control jumps to except. · โค้ดทำงานใน try; หากล้มเหลว การควบคุมจะกระโดดไป except
Write safe_int(text) that returns int(text). If the text is not a valid number, catch the ValueError and return -1 instead. · เขียน safe_int(text) ที่ คืนค่า int(text). หากข้อความไม่ใช่ตัวเลขที่ถูกต้อง ให้จับCaught ValueError และคืนค่า -1 แทน
Click Run to see the output here. · คลิก Run เพื่อดูผลลัพธ์ที่นี่
Write divide(a, b) that returns a / b. If b is 0, catch the ZeroDivisionError and return None instead. · เขียน divide(a, b) ที่ return a / b หาก b เป็น 0 ให้จับข้อผิดพลาด ZeroDivisionError และ return None แทน
Click Run to see the output here. · คลิก Run เพื่อดูผลลัพธ์ที่นี่
Write withdraw(balance, amount). If amount is more than balance, raise ValueError. Otherwise return the new balance (balance - amount). · เขียน withdraw(balance, amount) หาก amount มากกว่า balance ให้ raise ValueError มิฉะนั้น return ยอดคงเหลือใหม่ (balance - amount)
Click Run to see the output here. · คลิก Run เพื่อดูผลลัพธ์ที่นี่