Lojas
Lojas

Reputation: 205

How can i put an exception on EXC_BAD_INSTRUCTION?

I'm trying to put an exception for the following line:

let someData Int = Int(anArray[0])!

I want the exception so that it ignores it if its a string instead of an integer.

Im new to swift, but in python i could just do the following:

try:
    let someData Int = Int(anArray[0])!
except:
    pass

I've tried the following:

guard let someData Int = Int(anArray[0])! else {
    print("error")
}

,

let someData Int = try! Int(anArray[0])!

I'm using swift 3

Upvotes: 0

Views: 810

Answers (2)

David Pasztor
David Pasztor

Reputation: 54716

In Swift, try-catch blocks look like this:

do {
    //call a throwable function, such as 
    try JSONSerialization.data(withJSONObject: data)
} catch {
    //handle error
}

However, you can only catch errors from throwable functions, which are always marked with the throws keyword in the documentation. The try keyword can only be used on throwable functions and do-catch blocks only have an effect when you use the try keyword inside the do block.

You cannot catch other types of exceptions, such as force casting/unwrapping exception that you are trying to catch.

The proper way of handling Optional values if to use optional binding.

guard let someData = Int(anArray[0]) else {
    print("error")
    return //bear in mind that the else of a guard statement has to exit the scope
}

If you don't want to exit the scope:

if let someData = Int(anArray[0]) {
    //use the integer
} else {
    //not an integer, handle the issue gracefully
}

Upvotes: 1

rmaddy
rmaddy

Reputation: 318824

You missed the proper solution:

if let someData = Int(anArray[0]) {
    // someData is a valid Int
}

Or you can use guard:

guard let someData = Int(anArray[0]) else {
    return // not valid
}

// Use someData here

Note the complete lack of the use of !. Don't force-unwrap optionals unless you know it can't fail.

Upvotes: 1

Related Questions