DEV Community

Discussion on: The fight between Try-Catch and If-Else

Collapse
 
sfiquet profile image
Sylvie Fiquet

I don't see how you could use them interchangeably. If you're calling a function that generates exceptions, you should use try-catch (or decide that you'll let your program exit because it can't recover from that exception). If the function doesn't generate an exception but returns an error value then you use if. You don't have a choice.

The only question is when you design your own functions. Should this new function raise an exception when it fails or should it return an error? That's up to you. How bad is the failure? Does it need to interrupt the current task for special handling or can everything be handled easily by returning an error value? There's a performance cost that comes with exception handling so I'd say only use it when you can't do what you need with a return value.

Keep in mind that best practice for error handling might differ depending on the language you're using.