raisesアノテーション
失敗する可能性のある関数を示します
「raisesアノテーション」はCoddyKit上の無料Mojo Academyレッスンです。 これはレッスン3/4です。 下記で完全なレッスンを無料で読むことができます。その後、ブラウザ内の組み込みコードエディタと24時間対応のAIチューターでハンズオン演習できます。 これはMojo Academy学習パスの一部であり、ウェブとCoddyKitアプリ全体で進捗が同期されます。 Mojo Academyコースには全4レッスンが含まれています。
このレッスンの一部はまだ翻訳されておらず、英語で表示されています。
Honest About Failure
Mojo wants functions to be honest about whether they can fail. The raises keyword marks a function that might raise an error. 📣
Adding raises
Put raises right after the argument list. It tells callers this function may not always succeed.
fn parse(text: String) raises -> Int:
...def Can Always Raise
A flexible def function may raise without any annotation. Mojo treats def as able to fail by default.
def load(name: String):
raise Error("missing")fn Must Declare It
A strict fn function cannot raise unless you add raises. This makes failure explicit and easy to spot.
fn safe(x: Int) -> Int:
return x + 1Calling a raising Function
Calling something marked raises means you must handle the error, usually inside a try block.
try:
var n = parse("42")
except e:
print(e)Errors Bubble Through raises
If a raising function is called inside another raises function, the error simply propagates up without a try.
Non-raising Means Safe
A function without raises promises it will not raise. Callers can use it freely without try blocks.
The Compiler Checks You
Mojo's compiler rejects a raise inside a non-raising fn. This catches mismatches before your program ever runs.
Self-Documenting Code
The raises keyword acts as living documentation. One glance at the signature tells you if a call can fail.
Keep the Surface Small
Mark only the functions that truly can fail with raises. Fewer raising functions means simpler, safer call sites.
raises and Return Types
You combine raises with a normal return type. The function returns a value on success or raises on failure.
fn divide(a: Int, b: Int) raises -> Int:
if b == 0:
raise Error("divide by zero")
return a // bQuick Check
Think about how fn and the raises keyword work together.
Recap
You learned that raises declares a function may fail, that def can always raise while fn must opt in, and the compiler enforces it. 🎯
よくある質問
「raisesアノテーション」レッスンは無料ですか?
はい。「raisesアノテーション」の完全なテキストはこのウェブで無料で読めます。インタラクティブに演習し(組み込みコードエディタと24時間対応のAIチューター)、Mojo Academyコースの残りをアンロックするには、CoddyKit PROにアップグレードしてください。 Mojo Academyコースには全4レッスンが含まれています。
「raisesアノテーション」で何を学びますか?
失敗する可能性のある関数を示します ブラウザで直接実行するハンズオンコードでMojo Academyを演習し、24時間対応のAIチューターがレッスンを進める中での質問に答えます。
Mojo Academyを始めるのに経験は必要ですか?
事前経験は必要ありません。CoddyKitのMojo Academyは初級者から上級者向けに構成されているため、ここから始めるか最初から始めて、自分のペースで進むことができます。 これはレッスン3/4です。
「raisesアノテーション」レッスンにはどのくらい時間がかかりますか?
ほとんどのCoddyKitレッスンは約5~10分かかります。各レッスンはコンパクトでインタラクティブなので、着実に進歩し、ウェブとアプリ全体で正確に前回の場所から再開できます。
このMojo Academyレッスンでコードを書いて実行できますか?
はい。すべてのMojo Academyレッスンに組み込みコードエディタが含まれているため、ブラウザでリアルコードを書いて実行し、即座のAIフィードバックを取得できます。ローカル設定は不要です。
このコースのすべてのレッスン
- エラーを発生させる
- try/exceptで捕捉する
- raisesアノテーション
- finallyによる後処理