-1

I want to catch zero division error but do not know which exact pattern should I write for that

Result = try 5/0 catch {'EXIT',{badarith,_}} -> 0.

It works when I catch all the exceptions via

Result = try 5/0 catch _:_ -> 0.

but the first example gives

** exception error: an error occurred when evaluating an arithmetic expression

So how to properly catch zero division

Most Wanted
  • 6,254
  • 5
  • 53
  • 70

2 Answers2

4

You may use this code which I get from http://learnyousomeerlang.com/errors-and-exceptions

catcher(X,Y) ->
  case catch X/Y of
   {'EXIT', {badarith,_}} -> "uh oh";
   N -> N
  end.

6> c(exceptions).
{ok,exceptions}
7> exceptions:catcher(3,3).
1.0
8> exceptions:catcher(6,3).
2.0
9> exceptions:catcher(6,0).
"uh oh"

OR

catcher(X, Y) -> 
  try 
   X/Y 
  catch 
   error:badarith -> 0 
  end. 
Eugen Dubrovin
  • 888
  • 5
  • 15
2

If you are curious about exact exception which is thrown you can always find out in this way

1> try 5/0 catch Class:Reason -> {Class, Reason} end.
{error,badarith}
2> try 5/0 catch error:badarith -> ok end.
ok
3> try hd(ok), 5/0 catch error:badarith -> ok end.
** exception error: bad argument
4> try hd(ok), 5/0 catch Class2:Reason2 -> {Class2, Reason2} end.
{error,badarg}
5> try hd(ok), 5/0 catch error:badarg -> ok end.                 
ok

BTW, you should not use catch expression in most circumstances nowadays. It is considered obsolete expression and is kept mostly for backward compatibility and few special uses.

Hynek -Pichi- Vychodil
  • 26,174
  • 5
  • 52
  • 73
  • Thanks a lot! could you please also provide an example of correct approach which is used nowadays instead of a `catch` or link to some document where this fact is mentioned? – Most Wanted Jul 06 '18 at 13:39
  • 1
    @MostWanted I mean you should use `try ... catch ... end` instead of `catch` alone. When you use `catch` alone, you miss the class of exception. `try ... catch ... end` allows you to catch the only exception which you expect and intend to and let another exception throw anyway. If you use `catch`, you must rethrow the unwanted exception using `erlang:raise/3`. – Hynek -Pichi- Vychodil Jul 09 '18 at 07:02