Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Should you use try/catch/finally blocks often

As a developer with java background I am used to often catching exceptions to prevent them from crashing my app. This includes all kinds of delegate methods. Just an extra safety measure for unexpected situations.

My question is whether such approach is sensible in objective c and does it introduce some sort of performance problems? I other words would my app suffer in any way if I use try/catch blocks more often?

like image 352
gop Avatar asked Dec 18 '12 15:12

gop


2 Answers

It won't suffer that much, but you have to remember something. Unlike in other languages where you might have ConnectionRefusedException or FileNonexistantException, in objective-c, exceptions are programmer errors 90% of the time. So by the time your app enters production, it shouldn't have any exceptions anyway. Rather than, for example, catching out of bounds exceptions, just look at array length before trying. You can make a top level try-catch though just in case that gives the error and exits more gracefully than a crash.

like image 165
Linuxios Avatar answered Sep 28 '22 08:09

Linuxios


In general, you don’t want exceptions to occur while your program is running. So it’s considered better programming practice to test for errors before they occur rather than to catch them after they occur.

It’s also better to test for an error in a method and return some value as an error indicator than to throw an exception.Throwing exceptions use a lot of system resources, and, as such,

Apple generally recommends against using their unnecessary use (e.g., you don’t want to throw an exception simply because you can’t open a file).

like image 20
u.gen Avatar answered Sep 28 '22 06:09

u.gen