[Haskell-cafe] Use unsafePerformIO to catch Exception?

Henning Thielemann lemming at henning-thielemann.de
Mon Mar 23 20:10:59 EDT 2009

On Mon, 23 Mar 2009, Xiao-Yong Jin wrote:

> Hi,
> I just feel it is not comfortable to deal with exceptions
> only within IO monad, so I defined
>> tryArith :: a -> Either ArithException a
>> tryArith = unsafePerformIO . try . evaluate
> and it works quite good as
>> map (tryArith . (div 5)) [2,1,0,5]
> evaluates to
>> [Right 2,Right 5,Left divide by zero,Right 1]
> However, I guess unsafePerformIO definitely has a reason for
> its name.  As I read through the document in
> System.IO.Unsafe, I can't convince myself whether the use of
> 'tryArith' is indeed safe or unsafe.

Try to never use exception handling for catching programming errors! 
Division by zero is undefined, thus a programming error when it occurs.
   I'm afraid, a Maybe or Either or Exceptional (see explicit-exception 
package) return value is the only way to handle exceptional return values 
properly. Maybe in the larger context of your problem zero denominators 
can be avoided? Then go this way.

More information about the Haskell-Cafe mailing list