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.
Latest Answers