- The error function takes a string, and creates an exception. However, this exception is realizable only in the IO monad. Hence, we catch it while we are printing the result of div1.
- The function catch runs an IO action and takes a handler to catch the exception. It is possible to catch all exceptions by specifying the type of exception as SomeException.
- The try function also runs an IO action. However, it returns the result in Either e a where e is the exception and a is the result of the IO action. Thus, we can check using Either that we have a valid result.
- Typically, IO functions such as readFile raise an exception of type IOException.
- We can create custom exceptions by creating an instance of Show and Exception. The Show instance is required to show the exception in a user-friendly string. We can throw custom exceptions using the throw :: e -> a function. This is better than just error.
One must differentiate between an error and an exception. An error is a programming error and must be handled by a programmer. It represents certain assumptions or a case that is not handled. Exceptions, on the other hand, should be extremely rare and raised because of external factors rather than the program.