eli5: In programming, how does using “try and except/catch” blocks stop the program from crashing?

599 views

eli5: In programming, how does using “try and except/catch” blocks stop the program from crashing?

In: 10

20 Answers

Anonymous 0 Comments

It doesn’t stop it from crashing necessarily, but it can allow a program to deal with errors that come up.

Consider code that outputs 100 divided by user input. You could just “ask user for input, divide 100 by the user input, display the result”. But what if the user entered “0”? Or what if the user entered “TryingToBreakThisProgram”? In those cases, the code would be attempting to calculate “100/0” or “100/TryingToBreakThisProgram”, neither of which can be done. That makes the program crash. But a programmer could wrap the code in a “try” block, followed by a “catch” block. Once you’re in the catch block, there’s a variable that will tell you what caused the crash. So maybe in your catch block you have “if the error is a divide by zero error, tell the user that the number needs to be not zero”, or “if the error is that the value isn’t a number, tell the user that they need to enter a number”. And if it’s something else that you hadn’t anticipated, maybe you give up and let the program crash (that’s done by kind of “rethrowing” the error).

You are viewing 1 out of 20 answers, click here to view all answers.