I've read that Haskell can actually have runtime errors, despite being statically typed and functional. But, no one says what runtime errors those might be. Anyone know?
All the runtime exceptions may be throw by the standard libraries (the base
package) are defined in Control.Exception and GHC.Exception .
error
is a function defined in GHC.Err (based on GHC.Exception) as
error :: [Char] -> a
error s = raise# (errorCallException s)
It throws an ErrorCall
exception and print an error message to the stderr if isn't catched by some handler, most of the run-time exceptions raised by pure functions in base
are implemented by error
.
A few examples:
undefined
, a placeholder for code yet to be implemented, is defined as
undefined :: a
undefined = error "undefined"
It will pass the compilation step due to it's type and will raise an exception when it's evaluated at run-time.
The GHC standard library exports some partial functions by historical reasons, eg head
:
head :: [a] -> a
head (x:_) = x
head [] = badHead
badHead :: a
badHead = errorEmptyList "head"
errorEmptyList :: String -> a
errorEmptyList fun =
error (prel_list_str ++ fun ++ ": empty list")
IOException
concludes most of the ordinary IO exceptions you may have seen in other programming languages, eg FileNotFound, NoPermission, UnexpectedEOF etc. It's further extended in System.IO.Error
and is only throwed in the context of IO monad.
There are six arithmetic exceptions in base
, which are
data ArithException
= Overflow
| Underflow
| LossOfPrecision
| DivideByZero
| Denormal
| RatioZeroDenominator
Two array access exceptions, which are:
data ArrayException
= IndexOutOfBounds String
| UndefinedElement String
Four async exceptions, ie exceptions designed to be passed between processes, which are:
data AsyncException
= StackOverflow
| HeapOverflow
| ThreadKilled
| UserInterrupt
When a computation obviously won't terminate: NonTermination
When one or more processes are blocked forever: BlockedIndefinitelyOnMVar
, Deadlock
, etc.
When pattern matching failed (mainly in monads): PatternMatchFail
When an assertion failed: AssertionFailed
and much, much more.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.