Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Catch all errors, exceptions, no matter what it is, in Swift [duplicate]

Tags:

swift

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?

like image 867
Will Avatar asked Feb 18 '17 23:02

Will


People also ask

Why we should not catch exception?

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.

What is Nsexception in Swift?

An object that represents a special condition that interrupts the normal flow of program execution.

Do try catch block in Swift?

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 .


1 Answers

In Swift you can only catch errors that are thrown.

Since not all errors are handled by throwing (e.g. an out-of-range array access), you cannot catch everything.

like image 162
emlai Avatar answered Oct 20 '22 23:10

emlai