Precise exception type for division by zero in Erlang

409 views Asked by At

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

2

There are 2 answers

2
Eugen Dubrovin On BEST ANSWER

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. 
2
Hynek -Pichi- Vychodil On

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.