Try Catch vs If…Which to use?

When it comes to error handling while coding there are several options available. We have if statements, try and catch, throw exceptions or even handle the it silently by logging or just letting it go. So to make it simple I’ve come down to this simple question:

Do you know the intended response and are you not expecting an error?

  • If you answered yes, then use an if statement. If you know the possible outcomes then you can handle the response of the system.
  • If you answered no, the place the statement in try/catch block. If you don’t know what could possibly happen then don’t try to handle the outcomes until you know what you are dealing with.
As an added piece of precaution, you can always wrap a code block with try/catch to handle any possible unknown situation that may go wrong, even if you are already handling it through other conditional statements.

Leave a Reply

Your email address will not be published.