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

595 views

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

In: 10

20 Answers

Anonymous 0 Comments

“Can you go to the store and buy some ice cream?”

vs

“Can you go to the store and buy some ice cream? If they don’t have any, just come back home.”

Anonymous 0 Comments

An exception is generally used to handle a situation that a function is otherwise unable to handle. A function is ultimately set of instructions you run on a variable input, and sometimes that just won’t work.

For a basic real world example, let’s say you’re putting away groceries. Part of this is “hey, I’ve got a vegetable, let’s put it in the veggie drawer”. We could call this putInVeggieDrawer(vegetable). The steps of this function are open the fridge, open the veggie drawer, put the veggie in the drawer, close the drawer, close the fridge. You do this on a cabbage, a carrot, a leek, and then you try to do it on a pumpkin. Pumpkin doesn’t fit when you run the “put in drawer” step. We haven’t taken that situation into account, so we throw an exception. VeggieDrawerOutOfSpace exception.

Now, a program can only do what you have told it to do (you probably just told it badly if it’s doing something you don’t expect), so if we have to prepared for this, everything grinds to a halt.

So let’s say we want a contingency plan for a case where we get a VeggieDrawerOutOfSpace exception. We try the step that’s throwing it and catch the exception. If we get it, we want to execute an alternate set of instructions – put it in the root cellar instead. But we also want to make sure we’re always closing the veggie drawer and fridge, so we put those in a finally step so we do them even if we hit our exception on this step.

Generally, you want to be specific with your catches, and look for a specific type of exception. You don’t want to continue doing the same thing if you’ve actually got a FridgeOnFire exception – that’s a case to actually shut down the program entirely.

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.

Anonymous 0 Comments

If you really screw up at work, you might go to your boss for help. If he doesn’t know what to do, he asks his boss. So on and so forth until someone handles it or it gets to the CEO. When it gets to the CEO and he can’t handle it, he goes “We’re screwed shut the company down”. Your program just crashed.

Try catch is just “try this stuff, and if something goes wrong do this”.

You can also catch specific kinds of exceptions, like “I know how to handle this but if something else goes wrong I have to ask my boss”

Anonymous 0 Comments

Crashes happen when something goes wrong but wasn’t handled. Try/catch is basically “if something goes wrong, do this instead”.

Anonymous 0 Comments

It allows your program to run even when an exception (a kind of error) is thrown, it allows you to tell the program to do something else if it runs into an error instead of dying completely or continuously retrying.

Anonymous 0 Comments

Oke I’m a programmer(3 years now), can someone instead give me actual thing that’s happening at system level? Is it adding some sort of check before every part of the function is executed, is it moved to a separate place in memory or? I’ve tried googling this before but it still didn’t make sense to me.(feel free to use low level or assembly)

Anonymous 0 Comments

They don’t, really. Programs can crash in many, many ways that try-catch blocks can’t deal with. Things fundamental to the memory access or physical space it is running, or other things, like hardware, misbehaving.

Think of it the other way, focusing on why programs can choose to halt or not.

Your software is built so that even if it is well behaved, it will choose to halt if some condition happens – a signal is thrown to the top level of the program. The try-catch is a net to prevent some or all of those signals from making it up to the top level and halting the program, letting you handle it in a more sensible way.

This is done because it is easier to design all the halting conditions and then figure out how to handle large swaths of them than it is to design a handling mechanism local to each halting condition, or bake in the message passing for halting conditions explicitly to the calls originating anywhere and of any flavor.

Anonymous 0 Comments

Your dad asks you to get him a popsicle from the freezer. He’s giving you a piece of work to complete and is expecting a certain result. You go to the freezer but there are no popsicles, which means you aren’t able to complete the work as requested. This is a problem that somebody has to deal with.

You don’t know what to do so you report back to your dad that you can’t do what he asked. Now it’s his problem to deal with. Well, he was actually getting the popsicle for your mom, so he tells her he can’t do what she asked. Now it’s her problem to deal with. Well, she was going to give to the neighbour’s kid so now she has to tell him that there won’t be a popsicle. Now it’s the kid’s problem to deal with. He doesn’t know how to deal with it so he screams and cries and throws a tantrum.

That’s basically how exceptions work. Some piece of work couldn’t get done and the problem is reported back to whoever asked for the work to be done. This keeps going up the chain until it gets to the source, which is typically the thing that asked your program to run in the first place. And when it gets problems, it throws a tantrum and shuts down the whole program. We call this a crash.

A try/catch block, however, allows something to deal with problems instead of passing them along. You essentially “try” to do something and if it fails, then you “catch” the problem and deal with it however you want. So instead of your dad telling your mom that he can’t get her the popsicle, maybe he runs to the store and buys more. Now he’s dealt with the problem and the work can get done. Mom gets the result she expected and the kid stays happy. No crash.

You can be as specific or generic as you want with your catches as to the kinds of problems you want to be able to handle. Maybe your dad can deal with not having any popsicles left but he can’t deal with the freezer being on fire. So he can catch the “NoMorePopsiclesException” specifically and ignore everything else. Or maybe he does know how to deal that and can catch the “FreezerIsOnFireException” as well and solve that by doing something else (like using a fire extinguisher). Or maybe he’s super rich and his solution to every problem is to just buy a new house stocked with popsicles. So regardless of whether you’re just out of popsicles or the house is on fire, he deals with it by buying a new house. That would be a catch that just handles every kind of Exception.

Anonymous 0 Comments

You are baking a cake and measuring all the ingredients. If you are cracking eggs directly over the bowl that already has the other ingredients and one of the eggs is rotten you ruin everything in the bowl. If you crack the eggs into their own small bowl it allows you to find the rotten egg and get rid of just the egg, and try again, if the eggs are all good you add to the large bowl with everything else.