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

1.09K views

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

In: 10

20 Answers

Anonymous 0 Comments

Here’s an example with division by zero.

Y=1/X

Normally this code won’t crash. However, if X=0, then we have division by zero, which is undefined. This “throws” an exception to prevent the program from continuing in a potentially bad state. If the exception is not “caught”, then the program will crash.

“Try” is essentially a safety net that catches any exceptions that get thrown from that block of code, then executes the code in the “catch” block to figure out how to deal with it. So if we write:

Try {
Y=1/X
} catch {
Y=1
}

Then when X=0 the division by zero exception will be caught, Y will be set to a known safe value and the program will continue like normal. Try/catch statements can also be set up to handle specific exceptions in different ways. The example i gave above would handle *all* exceptions, not just division by zero. I might actually want the program to crash if some other exception is thrown, and just handle the division by zero. Syntax varies from language to language, but that would look something like this:

try {
Y=1/X
} catch(E) {
if (E==DIVISION_BY_ZERO) then {
Y=1
} else {
throw E
}
}

This version will allow the program to continue safely after catching a division by zero exception. But if any other exception is thrown, it will rethrow it, and crash the program assuming it wasn’t handled in another try/catch statement somewhere else.

Generally speaking exceptions are thrown when something doesn’t work correctly, and normally you would actually want the program to crash when these conditions aren’t dealt with.

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