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.
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:
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.
I suspect that you'd like to catch errors which is not explicitly marked with "throws".
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:
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