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.
エラーが発生した時
- ランタイムエラーは通常、プログラムをクラッシュさせます。
- 例外 (exception) はPythonによるエラー発生時のシグナルです。
- 例外処理により、エラーをキャッチして実行を継続できます。
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 / except
- リスクのあるコードを
try:ブロックに入れます。 - 例外が発生した場合、
except:ブロックが実行され、クラッシュしません。 - 問題がない場合、
exceptブロックはスキップされます。
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.
適切なエラーをキャッチする
- 予想されるエラーの種類を指定します:
except ValueError:。 ValueErrorは数値に対する無効なテキスト、ZeroDivisionErrorはゼロでの除算です。- 特定の種類のエラーをキャッチすることで、他のバグを隠蔽しません。
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.
finally と raise
finally:ブロックはエラーの有無に関わらず必ず実行され、クリーンアップに適しています。raiseは意図的にエラーをシグナルとして送信できます。- 例外がキャッチされない限り、
raise ValueError("message")はコードの実行を停止します。
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.
よくあるミス
- 具体的なエラー(
except ValueError:)を捉え、裸のexcept:を捉えないでください。 tryの中にリスクのある行のみを入れます。
Now you try
- Use
try/except(andraisein the last task). - Press Check answer to test your code.
あなたも試してみよう
try/exceptを使用します(最後のタスクではraiseも)。- 回答を確認 を押してコードを試してください。
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) となるようにする。テキストが無効な数字の場合、ValueError をキャッチして代わりに -1 を返回する。
Click Run to see the output here. · 実行ボタンをクリックして出力を確認してください。
Write divide(a, b) that returns a / b. If b is 0, catch the ZeroDivisionError and return None instead. · divide(a, b) を記述し、返回 a / b となるようにする。b が 0 の場合、ZeroDivisionError をキャッチして代わりに None を返回する。
Click Run to see the output here. · 実行ボタンをクリックして出力を確認してください。
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 。それ以外の場合は新しい残高(balance - amount)を return する。
Click Run to see the output here. · 実行ボタンをクリックして出力を確認してください。