For something like file not found the basic structure of the code below will work, but for this example of division by zero the exception is not caught. How does one catch a divide by zero?
import Control.Exception.Base
import Data.Array
main = toTry `catch` handler
toTry = do
print "hi"
print (show (3 `div` 0))
print "hi"
handler :: IOError -> IO ()
handler e = putStrLn "bad"
Any number divided by zero gives the answer “equal to infinity.” Unfortunately, no data structure in the world of programming can store an infinite amount of data. Hence, if any number is divided by zero, we get the arithmetic exception .
Microsoft Excel shows the #DIV/0! error when a number is divided by zero (0). It happens when you enter a simple formula like =5/0, or when a formula refers to a cell that has 0 or is blank, as shown in this picture.
Any number divided by 0 is undefined, mathematically speaking.
The div function requires arguments whose type is in the class Integral, and performs integer division. More precisely, div and mod round toward negative infinity. Their cousins, quot and rem , behave like integer division in C and round toward zero.
You need a handler that catches an ArithException, and matches on DivideByZero
.
import Control.Exception.Base
import Data.Array
main = toTry `catch` handler
toTry = do
print "hi"
print (show (3 `div` 0))
print "hi"
handler :: ArithException -> IO ()
handler DivideByZero = putStrLn "Divide by Zero!"
handler _ = putStrLn "Some other error..."
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With