Is this usage not correct? why? The file name I use is correct!
on the right side of the playground I would aspect to see the content of the txt file.
In terms of why this failed, you'd have to look at the error
object and examine why it failed. You're catching the error
, so look at it:
func read(path: String) throws {
do {
try NSString(contentsOfFile: path, encoding: NSUTF8StringEncoding)
} catch {
print("cannot read: \(error)")
}
}
That will tell you why it failed.
Having said all of that, this doesn't quite make sense: First, you're reading the contents of the path into the NSString
, but discarding it. You presumably want to return this string or do something with it.
Second, read
has been declared in such a way as to say that it throws
error, but it doesn't really. It catches any error that might happen itself, but doesn't throw anything. You have to decide whether read
will throw any errors it generates, or whether it will handle them without throwing any error, or both.
Assuming the caller was going to handle the error, you might just forego any do
-try
-catch
construct in read
altogether:
func read(path: String) throws -> NSString? {
return try NSString(contentsOfFile: path, encoding: NSUTF8StringEncoding)
}
Then you can let the caller catch any error that NSString
threw. For example, you might catch the "not found" error:
do {
let string = try read(path)
// do something with string
} catch let error as NSError where error.domain == NSCocoaErrorDomain && error.code == NSCocoaError.FileReadNoSuchFileError.rawValue {
// not found handling here
} catch {
print(error)
}
If you really wanted read
to not only catch the error, but also make sure it throws
one as well, then you'd need to have to explicitly throw
an error from its catch
block. You can use this pattern using either your own ErrorType
or just throwing the original error you just caught:
func read(path: String) throws -> NSString? {
var string: NSString?
do {
string = try NSString(contentsOfFile: path, encoding: NSUTF8StringEncoding)
} catch {
// do whatever special handling you want here
// but also throw error so caller is informed that there was an issue
throw error
}
return string
}
Frankly, I think the pattern outlined above is simpler, but given your code snippet, I thought I'd also illustrate this latter pattern, too, in case you needed something like that.
I am also learning, so I wrote a little demo. Hope it helps.
catch let error as NSError { print(error.localizedDescription) }
to get a possible error description.