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