Krish  gopi
Krish gopi

Reputation: 155

Try catch example in Erlang

I followed the documentation but didn't understand try catch, could somebody please explain with a simple example?

Upvotes: 1

Views: 5365

Answers (3)

2240
2240

Reputation: 1710

If you want a single-line example to use in your Erlang shell:

1> try exit(timeout) of _ -> not_caught catch exit:timeout -> ok end.
ok

You can open the shell by running erl. I would recommend LYSE.

Upvotes: 1

Nils
Nils

Reputation: 313

The idea behind try catch is to try an expression and catch it if anything goes wrong. You first try the expression, and if everything goes well, you will get the normal result. But if you run into an error instead, you can catch it and handle it.

For example, taking the head of an empty list would result in a 'bad argument' exception. You can for instance catch that and return the error type, or catch all patterns and return whatever you like. Try it out in the Erlang shell!

    1> try hd(["foo","bar"]) catch error:Error -> {error,Error} end.
    "foo"
    2> try hd([]) catch error:Error -> {error,Error} end.
{error,badarg}
    3> try hd([]) catch _:_ -> "Can't take the head of an empty list" end.
"Can't take the head of an empty list"

Upvotes: 2

fenollp
fenollp

Reputation: 2496

I think you'll like LYSE's article on exceptions.

Upvotes: 7

Related Questions