I'm new to Swift and I have a little problem.
I have a piece of code, and any line could potentially throw an error.
My problem is, I don't want to go through line by line catching each error, I want to catch them all in one statement.
In python you can do this
try:
exampleArray = [1,2,3,4]
print(exampleArray[4])
except Exception as e:
print(e)
pass
What that does is try to print a value from the array that doesn't exist, but it is caught by the except
statement, I am wondering whether something this easy exists in Swift
To clarify, I am not trying to catch an index out of range
error, I just want to catch an error, no matter what it is.
Is it possible without declaring my own errors, and throwing them line by line?
Because when you catch exception you're supposed to handle it properly. And you cannot expect to handle all kind of exceptions in your code. Also when you catch all exceptions, you may get an exception that cannot deal with and prevent code that is upper in the stack to handle it properly.
An object that represents a special condition that interrupts the normal flow of program execution.
The try/catch syntax was added in Swift 2.0 to make exception handling clearer and safer. It's made up of three parts: do starts a block of code that might fail, catch is where execution gets transferred if any errors occur, and any function calls that might fail need to be called using try .
In Swift you can only catch errors that are throw
n.
Since not all errors are handled by throw
ing (e.g. an out-of-range array access), you cannot catch everything.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With