lean-ja / lean-ja/lean-by-example
panic! と throw の違い
Nobody has claimed this yet.
- Dominant language
- Lean
- Stars
- 188
- Forks
- 15
- Avg merge
- 9h 8m
- Merged PRs (30d)
- 6
Description
panic! はプログラムを止めないよ!
Lean で panic! マクロを使ったとき、
panic! "Something went wrong!"
って書くと「止まる」と思うかもしれないけど……実は止まらないの!
どうなるの?
panic!は単にエラーメッセージを出すだけで、- プログラムの実行はそのまま続いちゃうの。
たとえば Option.get! で none を強引に取り出しても、
panic! が呼ばれるだけで、「例外」にはならず、ただ default の値を返すだけなの。
これは、Lean の安全性(safe)を保つための設計なんだけど、
意図せず危険な動作を通してしまう可能性があるの。
たとえば:
def unsafeDiv (x y : Nat) : Nat :=
if y == 0 then panic! "division by zero" else x / y
#eval unsafeDiv 10 0 -- => prints panic but returns 0
panic! が表示されるけど、プログラムはそのまま動いて
0(= Nat.default)が返ってきちゃうの。こわ〜い!
解決策は?
Lean の実行時に環境変数を設定することで、
本当に「パニックして止まる」ようにできるの:
LEAN_ABORT_ON_PANIC=1
でもこれは環境変数だから、ユーザー向けのアプリケーションなどでは
ちゃんと機能しないこともあるの。
じゃあどうしたらいいの?
安全のためには、
panic!に頼らず、ちゃんとExceptやOptionのチェックを使う- 本当に止めたいときは明示的に
throwやIO.userErrorを使う
などを検討してね♪
Contributor guide
First steps
- Read the whole issue, then the project's contributing guide.
- Comment on the issue to say you are picking it up — it saves two people doing the same work.
- Fork the repository and make your change on a branch.
- Open a pull request that references the issue number.
Research direction
No file, test, or entry point is named. First identify where this explanation belongs in the Lean-by-example documentation, then confirm the intended behavior and define the documentation change before starting; the issue does not currently state what completion should look like.
Written by the indexing model from the issue text.
Assessment
- Domain
- documentation
- Issue type
- Documentation
- Difficulty
- 3/5
- Estimated time
- 1-2 days
- Activity status
- Stale
- Clarity
- Needs clarification
- Newbie friendliness
- 30/100