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
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.
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
}