r/PHPhelp • • Dec 28 '21

Solved My try/catch and error throwing knowledge is really lacking

Hi, My try/catch and error throwing knowledge is really lacking. Is there some resource, tutorial, or video that explains everything about these related concepts in a way that really dumbs it down for those of us that are not blessed with good comprehension skills.

Thanks.

8 Upvotes

6 comments sorted by

13

u/HolyGonzo Dec 28 '21

First thing to realize is that try/catch doesn't make anything WORK but rather it just makes it easier and cleaner to handle problems that MIGHT come up.

Imagine you're making a dinner by following a recipe. But let's say that at the very beginning, you realize that you don't have all the ingredients. So you keep trying to make the recipe anyway, right?

No, of course not. If you've figured out that there is a significant problem that will keep you from successfully completing the recipe, then you stop what you're doing. Otherwise you will just keep going and you'll end up making -something- but it sure won't be what you -intended- to make.

And if you can't make the recipe, then you probably want to tell someone why, or maybe you want to do something about it (go buy the missing ingredients) and try again.

This is basically the whole try/catch concept.

Very often you have code that will only run successfully if there was some other, previous code that succeeded. For example, just like you can't cook a meal without ingredients, you can't query a database without first having a successful database connection.

So the try { } block contains all the steps to take that will all hopefully go right. But if one step goes WRONG, then you can stop things at that point, so the rest of the steps inside the try { } aren't even attempted/tried. You do this by "throwing an Exception." So an exception is simply an elaborate error. When you throw an exception inside of a try { } section, it stops executing the rest of the stuff inside that section and instead skips down to the "catch" section, which is the code that catches the exceptions that you have thrown, so that the errors can all be handled in a very nice, clean, consistent way.

So a try / catch block with a recipe might look like this:

try
{
  if(ingredients are missing)
  {
    throw new \Exception("Missing ingredients");
  }

  $batter = mix flour and stuff;
  if($batter isn't right)
  {
    throw new \Exception("The batter wasn't the right consistency");
  }

  $cake = bake batter in oven;
  if($cake is burned)
  {
     throw new \Exception("Cooked the batter too long");
  }
  if($cake is still batter)
  {
    throw new \Exception("Oven didn't turn on");
  }
  
  write_in_diary("Dear diary, I successfully made a cake today!");
}
catch(\Exception $ex)
{
  write_in_diary("Dear diary, I tried to make a cake today but it failed because: " . $ex->getMessage());
}

So you can see how the try { } block contained all the different steps, ideally ending in success and a successful entry in our diary, but the code checks the success of each step so that if a step fails, the recipe attempt stops right there and we write about the failure in our diary.

In code, our "diary" would probably be some kind of error log somewhere. That way we can know if something went wrong and why.

There are some functions in PHP that are already written to throw Exceptions if they fail but not a lot of them do yet.

There are more concepts to learn about it but that's a really quick crash course on the basics.

2

u/[deleted] Dec 28 '21

That was great, thanks. I guess I do something very similar already, but without the try catch. That is, I do something, then check the result. If there's an error, I set an error flag and message. Then I check for the error flag at the other parts of the app before continuing. But try catch looks like a cleaner way of doing it.

2

u/HolyGonzo Dec 28 '21

Yep, a lot of these things come about because they make so much sense that everyone is doing them or some variation of them. Given that, it just makes sense to bake the functionality directly into the language to make it as easy to do as possible.

One additional nice thing about try/catch is that many of the major languages have it, not just PHP, and the syntax is often really similar, if not identical. For example, if you know how to write a try/catch block in PHP, then you already know how to do it in C#.

6

u/DesignatedDecoy Dec 28 '21

One small addition is the finally block that would include cleaning up all of the mess of the cake regardless of whether or not it was cooked properly.

2

u/HolyGonzo Dec 28 '21

Yep. Just to keep it to the basics,I skipped over the finally block as well as catching multiple exception types. But good addition to the analogy!