In the documentation for Control.Exception in base 4.4.0.0 there is an example of how to make exception hierarchies. The example shows how one can catch generalizations of a specific exceptions by declaring instances of the Exception class in terms of the parent exception. This is cool, but how do I make my exceptions children of existing exceptions. For example, I want to make exceptions that are caught by type constraints on IOException. The example in Control.Exception shows this:
*Main> throw MismatchedParentheses catch (\e -> putStrLn ("Caught " ++ show (e :: SomeCompilerException)))
Caught MismatchedParentheses
*Main> throw MismatchedParentheses catch (\e -> putStrLn ("Caught " ++ show (e :: IOException)))
*** Exception: MismatchedParentheses
How can I get IOException constraints to catch my exceptions?
You can't. IOException
is not designed to be extensible in such a way.
In general, you cannot extend existing data types willy-nilly. There's a good reason for that, as it would require existing functions to know what to do with the new values. There are ways around this, but they all require the data type to be designed with this in mind.
It's not clear to me why you want your custom exceptions to be treated like IO exceptions, though. If you want to catch both types, just nest applications of catch
, one for each type. Or perhaps it would be better to turn things around and allow IO exceptions to be wrapped within your own exception type. The documentation already has good examples of how to do that. It all comes down to what you're trying to achieve.
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