I cannot catch error using Try-Catch on Swift

Asked

Viewed 237 times

2

I’m making a app, which is giving me a certain error at some point, but is only occurring on certain devices. I am trying to capture this error with the do/catch, but I’m having trouble catching him.

The code is as follows:

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 may occur within this method?

  • 1

    syntax is correct, you would have to see how you launch Exception within the initApp method

  • what is the exception? Remembering that Swift’s Try-catch only captures Swift exceptions if its exception is Obj-c will continue to give error.

  • Post what the method initApp() makes it hard to imagine out of nowhere where the mistake might be.

1 answer

1

Look at, try catch does not capture only pointers of NSError, they serve to capture exceptions in accordance with the protocol ErrorType.

How will you know when it is possible to capture an Exception? What type of Exception? And how you can also use this feature to throw errors from your code?

On Swift 2, you will have two situations:

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

In Objective-C, some methods receive as a parameter, a pointer to an error, 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.
}

Okay, now that it should be 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 receive an Nserror pointer, do not receive a Swift pointer, they throw an exception and this is visible right at the signature of the method:

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

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

Okay knowing this, you MUST put any execution of this (or any method marked with throw) within a block of exception manipulation try catch. But in this case, you will not receive 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 capture 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 may throw an exception

Let’s assume, that you want to implement a hypothetical function that, convert strings into numbers ok?

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

Using this method would be as simple as that:

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

Okay looks like it works, but what if by chance someone passes a different string?

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

This is the kind of method that can surely go wrong, so so that the program does not stop running and you can signal who is using in order to fix the problem, you can use a protocol ErrorType to throw custom errors and give the hint of how to fix it.

Let’s make a ErrorType very simple for this case:

Enum Stringtointerror: Errortype { case Notanumber }

This enumerator, serves to signal a type of error. Let’s now change the method convertToInt, so that he can hurl 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, every time i optionally for nil, the method will throw the error StringToIntError.NotANUmber.

Now we can use the method convertToInt more safely, this way:

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

Well, I know the explanation got a little long, but that’s a summary of how to work error treatments at SWIFT.

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

Have a nice code.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.