Reputation:
Ok, guys, super easy question (it seems weird that Google didn't help me with this one):
import IO
--.... yadda, yadda, yadda
file <- openFile "/some/path" ReadMode
How do I check if the handle that I got from openFile
is a valid handle, i.e. that the file exists and was opened successfully?
Upvotes: 6
Views: 2178
Reputation: 137987
If the file doesn't exist, or some other error occurs, the call to openFile
will fail with an exception.
For example:
import System.IO
main = do
openFile "/some/path" ReadMode
Fails with:
A.hs: /some/path: openFile: does not exist (No such file or directory)
The types of exception that may be thrown by openFile
are listed here, and include:
You can catch these errors using Control.Exception, like so:
{-# LANGUAGE ScopedTypeVariables #-}
import System.IO
import Control.Exception
main = do
handle (\(e :: IOException) -> print e >> return Nothing) $ do
h <- openFile "/some/path" ReadMode
return (Just h)
Upvotes: 7