Is there a way to NOT modify IORef value if error happens inside modifyIORef
?
import Data.IORef
main = do
a <- newIORef (1::Int)
-- a keeps error now, not Int
modifyIORef a (const $ error "Error forever")
val <- readIORef a -- val is error now
putStrLn $ "Result: " ++ show val -- throws error
Haskell does not do error handling in the same way that other languages, such as Python and Java, do. When you call the
error
function, the program will halt. Period. The error cannot be caught. There is no way of redirecting it, or restarting the program. Theerror
function raises an error, not an exception. If you want to represent the idea of failure in Haskell, you use theMaybe
andEither
monads. Below is how you might implement the functionality that you want using theEither
monad.EDIT: As dfeuer kindly pointed out in his comment, it is possible to intercept errors in GHC. It is, however, considered bad practice except in very specific circumstances, so using the
Maybe
andEither
types is still preferred.