In Swift 3.0 , how to implement generic do-try-catch block to catch all errors that are thrown as a result of an operation. Apple documentation says to implement a enumerator of type ErrorType , which lists errors that are thrown. Suppose if we don't know what sort of errors that can be thrown by a operation then how to implement it. Below code is only for illustration purpose. Here i can catch the error but i don't know what causes this error. In objective C, we can get exact reason why error happened but here we only get the information that we have assigned to it.
enum AwfulError: ErrorType{
case CannotConvertStringToIntegertype
case general(String)}
func ConvertStringToInt( str : String) throws -> Int
{
if (Int(str) != nil) {
return Int(str)!
}
else {
throw AwfulError.general("Oops something went wrong")
}
}
let val = "123a"
do {
let intval: Int = try ConvertStringToInt(val)
print("int value is : \(intval)")
}
catch let error as NSError {
print("Caught error \(error.localizedDescription)")
}
I have found solution to my question.Code structure is listed below.
do {
let str = try NSString(contentsOfFile: "Foo.bar",encoding: NSUTF8StringEncoding)
print(str)
}
catch let error as NSError {
print(error.localizedDescription)
}
Below code doesn't work because try expression is returning nil .To throw a error try expression should return a error and not a nil value. Type cast operation is an optional.
do {
let intval = try Int("123q")
print( Int("\(intval)"))
}
catch let error as NSError {
print(error.localizedDescription)
}