DEV Community

Cover image for Interview Question: Conditional statements
Daniel Lee
Daniel Lee

Posted on • Updated on

Interview Question: Conditional statements

Hi community! I'm Daniel, a senior computer science undergraduate in Canada, going through tough time (like everyone else) to find meaningful career after graduation. I'm here today to share something that came up during recent interviews.

So, I recently had an interview for a junior software developer and I was asked this question:

"What do you know about error handling?"
"What differentiates try-catch block from if-else block?"

I roughly knew at that time that try-catch block allows more freedom to choose exception handling cases. For example, you can write your own error exception handling cases or use one of the built-in libraries to catch a variety of cases. This is somewhat true, but not the type of answer the interviewer was looking for.

   // code to try
}catch(exception e){
   // code to handle errors
Enter fullscreen mode Exit fullscreen mode

In fact, you can also write functions to handle errors if you were to use if-else block. Then what the heck is the real difference I thought to myself?

It turns out the try-catch block is better when you are uncertain about what errors will be thrown. For example, your program breaks and your try-catch block throws an exception. When using the try-catch block, it will provide you meaningful error message to modify your program easily. The more information there is about an error, the better you can handle the error and modify your program accordingly.

On the other hand, when the if-else block is used, it doesn't have the same luxurious functionality. Before writing any conditional statement, you are supposed to know exactly what type of error will occur when specific cases are triggered. Although you may write your functions to handle specific cases, but one can be always certain about how a program is going to act.

Therefore, it is generally considered a good practice to use try-catch block for error handling when you are uncertain about how your program is going to act. If-else block is preferred when you are 100% certain how your program is going to act and when it's going to throw errors.

So, here're my takeaways:

  • Elaboration and Exemplification are very important
  • Don't just write code, understand concepts and its features
  • Think positive, you learned something new that is stupid enough not to know. So, you are advanced to being less stupid :)
  • School doesn't teach this kind of stuff, invest more time to learn things on your own

Discussion (0)