try/exceptで捕捉する
失敗から適切に復旧します
「try/exceptで捕捉する」はCoddyKit上の無料Mojo Academyレッスンです。 これはレッスン2/4です。 下記で完全なレッスンを無料で読むことができます。その後、ブラウザ内の組み込みコードエディタと24時間対応のAIチューターでハンズオン演習できます。 これはMojo Academy学習パスの一部であり、ウェブとCoddyKitアプリ全体で進捗が同期されます。 Mojo Academyコースには全4レッスンが含まれています。
このレッスンの一部はまだ翻訳されておらず、英語で表示されています。
Catching the Fall
Raising signals a problem, but someone must catch it. Mojo uses a try block to run risky code and recover if it fails. 🪤
The try Block
Code that might fail goes inside try. If it raises, Mojo jumps straight to the matching recovery code below.
try:
risky_step()The except Block
The except block holds your recovery plan. It only runs when the try block actually raised an error.
try:
risky_step()
except:
print("recovered")Reading the Error
You can name the caught error to read its message. Here e holds the details of what went wrong.
try:
risky_step()
except e:
print("failed:", e)Normal Path First
If nothing raises, the try block finishes and the except block is skipped entirely. The happy path stays clean.
Recovering Gracefully
Catching lets you show a friendly message or use a fallback value instead of letting the whole program crash. ✨
Keep try Blocks Small
Wrap only the risky line in try, not your whole function. Small blocks make it clear what could fail.
Catching Calls That Raise
Calling a function that may raise requires a try. Here we safely attempt a withdrawal and handle a rejection.
try:
withdraw(-5)
except e:
print("denied:", e)Don't Swallow Silently
An empty except that does nothing hides bugs. At minimum log the error so problems stay visible.
Catch Where You Can Help
Only catch an error where you can actually do something useful about it. Otherwise let it propagate upward.
Try Plus Except as a Pair
Together try and except turn a possible failure into a controlled outcome your program can continue past.
Quick Check
Recall when each block of a try/except actually runs.
Recap
You learned to wrap risky code in try, recover in except, read the error with a name, and keep blocks small and meaningful. 🎯
よくある質問
「try/exceptで捕捉する」レッスンは無料ですか?
はい。「try/exceptで捕捉する」の完全なテキストはこのウェブで無料で読めます。インタラクティブに演習し(組み込みコードエディタと24時間対応のAIチューター)、Mojo Academyコースの残りをアンロックするには、CoddyKit PROにアップグレードしてください。 Mojo Academyコースには全4レッスンが含まれています。
「try/exceptで捕捉する」で何を学びますか?
失敗から適切に復旧します ブラウザで直接実行するハンズオンコードでMojo Academyを演習し、24時間対応のAIチューターがレッスンを進める中での質問に答えます。
Mojo Academyを始めるのに経験は必要ですか?
事前経験は必要ありません。CoddyKitのMojo Academyは初級者から上級者向けに構成されているため、ここから始めるか最初から始めて、自分のペースで進むことができます。 これはレッスン2/4です。
「try/exceptで捕捉する」レッスンにはどのくらい時間がかかりますか?
ほとんどのCoddyKitレッスンは約5~10分かかります。各レッスンはコンパクトでインタラクティブなので、着実に進歩し、ウェブとアプリ全体で正確に前回の場所から再開できます。
このMojo Academyレッスンでコードを書いて実行できますか?
はい。すべてのMojo Academyレッスンに組み込みコードエディタが含まれているため、ブラウザでリアルコードを書いて実行し、即座のAIフィードバックを取得できます。ローカル設定は不要です。
このコースのすべてのレッスン
- エラーを発生させる
- try/exceptで捕捉する
- raisesアノテーション
- finallyによる後処理