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

1.23K views

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

In: 10

20 Answers

Anonymous 0 Comments

Sometimes it depends on your definition of “crashing”

Consider a simple function that divides two numbers. Given A and B, it returns A/B. Obviously, this is undefined for B=0. If you ignore this, the program will “crash hard” when given B=0. the error will originate from some part of the architecture below the program you’re writing, and you will have limited control over how it is handled. Depending on the environment, it might send no information to the user about what happened, or that information could be unhelpful for diagnosing the problem.

However, you can put in code to catch the problem by testing for B=0 before doing the calculation. If it finds that B=0, it could return a helpful error message to the user telling them to try a different value for B. Depending on the application, you could also choose some fallback behavior like setting B to a very small nonzero number.

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