In Swift 3.0, how to implement a common try-try-catch block to catch all errors that result from an operation. Apple's documentation talks about introducing an ErrorType enumerator that lists errors that occur. Suppose, if we do not know what errors can be caused by an operation, then how to implement it. The code below is for illustration purposes only. Here I can catch the error, but I do not know what causes this error. In object C, we can get the exact cause of the error, but here we get only the information that we 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 found a solution to my question. The code structure is given below.
do {
let str = try NSString(contentsOfFile: "Foo.bar",encoding: NSUTF8StringEncoding)
print(str)
}
catch let error as NSError {
print(error.localizedDescription)
}
, try nil. , try , nil. .
do {
let intval = try Int("123q")
print( Int("\(intval)"))
}
catch let error as NSError {
print(error.localizedDescription)
}