I can not catch error using Try-Catch in Swift

2

I am making an app , which is giving me a certain error at some point, but it is only occurring on certain devices. I'm trying to catch this error with do/catch , but I'm not able to capture it.

The code looks like this:

do {
    try self.minhaFuncao()
} catch let error1 as NSError {
    self.enviarEmailComErro(error1.description)
}

I know the error is located in minhaFuncao() , code:

func initApp() throws {
    //Faço várias coisas aqui
}

How do I capture these errors that can occur within this method?

    
asked by anonymous 04.12.2015 / 19:51

1 answer

1

Well, try catch does not only catch pointers of NSError , they are used to catch exceptions that conform to the ErrorType protocol.

How will you know when it's possible to catch an exception? What kind of exception? And how can you also use this feature to flip errors from your code?

In Swift 2, you will have two situations:

1. Objective-C methods that mark errors in its execution

In Objective-C, some methods get a pointer to an error as a parameter, this pointer serves to signal the developer that, if something goes wrong, you need to do something about the failure.

An example:

NSError *error;

NSString *someString = [NSString stringWithContentsOfURL: url, encoding: NSUTF8StringEncoding, &error];

// Se o ponteiro definido no ultimo parâmetro não for nil, significa que algo deu errado.
if ( error ) {
  // caso algo de errado, faça algo aqui.
}

Ok, now that it should have been clear how to do this in Objective-C, let's see how to do the same thing in Swift.

The first thing to keep in mind is that, from Swift 2, all methods in Objective-C that get an NSError pointer, do not get a pointer in Swift, they throw an exception and this is visible soon on method signature:

convenience init(contentsOfURL url: NSURL, encoding enc: UInt) throws

Notice the throws at the end of the signature of the same method that I showed in Objective-C.

Okay, knowing that you should MUST put any of this (or any throw-marked method) within a block of try catch exception handling. But in this case, you will not get an exception, but a NSError , as described in the documentation:

  

In Swift, this method returns a nonoptional result and is marked with the throws keyword to indicate that it throws an error in cases of failure.

To catch these possible errors, you use the following Swift implementation:

do {
  let str = try NSString(contentsOfURL: url, enconding: NSUTF8StringEncoding)
}
catch let error as NSError {
  // caso algo de errado, faça algo aqui
}

2. Methods that can throw an exception

Let's assume, you want to implement a hypothetical function that, do the conversion of strings into numbers ok?

func convertToInt (string: String) -> Int {
  return Int(string)!
}

Using this method would be as simple as this:

let str = "12345"
let int = convertToInt(str) // int = 1234 literal

Okay it seems to work, but what if, by chance, does someone pass a different string?

let str = "1234a"
let int convertToInt(str) // Error

This is the kind of method that can certainly go wrong, so that the program does not stop executing and you can signal who is using it to correct the problem, you can use a ErrorType protocol to throw errors customized and give the hint how to fix it.

Let's make a simple ErrorType for this case:

enum StringToIntError: ErrorType {   case NotANumber }

This enumerator serves to signal a type of error. Let's now change the convertToInt method so that it can fling this error if the return "is not a number."

func convertToInt (string: String) throws -> Int {
  let i: Int? = Int(string);

  guard (i != nil) else { throw StringToIntError.NotANumber }

  return i!
}

So now, whenever% with optionally is nil, the method will throw the error i .

Now we can use the StringToIntError.NotANUmber method more securely, like this:

do {
  let int2 = try convertToInt(str2)
  print( int2 )
}
catch StringToIntError.NotANumber {
  print( "Não é um número" )
}

Well, I know the explanation got a bit long, but that's a summary of how to work with error treatments on Swift.

I hope this can help you understand your problem and fix it.

Have a nice code.

    
11.05.2016 / 16:02