Haskell - Checking the Validity of a File Handle
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?
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:
- isAlreadyInUseError if the file is already open and cannot be reopened;
- isDoesNotExistError if the file does not exist; or
- isPermissionError if the user does not have permission to open the file.
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)
精彩评论