Created
July 11, 2012 21:30
-
-
Save theburningmonk/3093711 to your computer and use it in GitHub Desktop.
Erlang exception handling example
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| -module(exceptions). | |
| -export([sword/1, talk/0, black_knight/1]). | |
| sword(1) -> throw(slice); | |
| sword(2) -> erlang:error(cut_arm); | |
| sword(3) -> exit(cut_leg); | |
| sword(4) -> throw(punch); | |
| sword(5) -> exit(cross_bridge). | |
| talk() -> "blah blah". | |
| black_knight(Attack) when is_function(Attack, 0) -> | |
| try Attack() of | |
| _ -> "None shall pass." | |
| catch | |
| throw:slice -> "It is but a scratch."; | |
| error:cut_arm -> "I've had worse."; | |
| exit: cut_leg -> "Come on you pansy!"; | |
| _:_ -> "Just a flesh wound." | |
| end. | |
| %% run these into the shell | |
| 1> c(exceptions). | |
| {ok,exceptions} | |
| 2> exceptions:black_knight(fun exceptions:talk/0). | |
| "None shall pass." | |
| 3> exceptions:black_knight(fun () -> exceptions:sword(1) end). | |
| "It is but a scratch." | |
| 4> exceptions:black_knight(fun () -> exceptions:sword(2) end). | |
| "I've had worse." | |
| 5> exceptions:black_knight(fun () -> exceptions:sword(3) end). | |
| "Come on you pansy!" | |
| 6> exceptions:black_knight(fun () -> exceptions:sword(4) end). | |
| "Just a flesh wound." | |
| 7> exceptions:black_knight(fun () -> exceptions:sword(5) end). | |
| "Just a flesh wound." |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment