Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Swift Error Handling For Methods That Do Not Throw [duplicate]

Tags:

How to handle errors for methods or code that does not explicitly throw?

Wrapping it a do / catch block results in a compiler warning:

"'catch' block is unreachable because no errors are thrown in 'do' block" 

Coming from C# / JAVA background this is an oddity to say the least. As a developer I should be able to safeguard and wrap any code block in do/catch block. Just because a method is not explicitly marked with "throw" does not mean that errors will not occur.

like image 502
AlexVPerl Avatar asked Feb 02 '17 05:02

AlexVPerl


2 Answers

What you are asking is not possible in Swift, as Swift has no facility to handle runtime errors such as out-of-bounds, access violations or failed forced unwrapping during runtime. Your application will terminate if any of these serious programming errors will occur.

Some pointers:

  • Q: How to handle EXC_BAD_ACCESS? A: Not possible
  • Q: How to handle failed forced unwrap? A: Not possible
  • Q: How to handle array out of bounds? A: Not possible

Long story short: Don't short-cut error handling in Swift. Play it safe, always.

Workaround: If you absolutely must catch runtime-errors, you must use process boundaries to guard. Run another program/process and communicate using pipes, sockets, etc.

like image 158
Christopher Oezbek Avatar answered Sep 18 '22 05:09

Christopher Oezbek


I suspect that you'd like to catch errors which is not explicitly marked with "throws".

enter image description here

This makes no sense. You cannot catch other than errors which is explicitly marked with "throws". So, this warning is valid.

For this example, if executed, fatal error: Index out of range will occur. This is runtime error, and you cannot catch it.

For this example, you should check elements size like this, instead of doing try-catch error handling:

enter image description here

like image 34
mono Avatar answered Sep 19 '22 05:09

mono