PHP Exception Handling: UnexpectedValueException

Today we’ll look at UnexpectedValueException – the runtime-only version of  UnexpectedValueException. Read on to see how to add this to your PHP exception handling repertoire!

The Technical Rundown:

  • All SPL exceptions extend either LogicException or RuntimeException. UnexpectedValueException extends RuntimeException.
  • UnexpectedValueException is thrown if a value does not match with a set of values.

When Should You Use it?

To learn more about UnexpectedValueException, we’re going to make a salad using the makeSalad() function below.

<?php

  function makeSalad(){
    $ingredients = getIngredients();
    $salad = combineIngredients($ingredients);

    return $salad;
  }

  makeSalad();

?>

How do you make a salad? You get the ingredients and you combine them (I know it’s not always this simple but…this works as an example, so…). The functions in our makeSalad() function appear to do just that. Perfect!

But what if there are no ingredients left? You can’t exactly make a salad – or anything for that matter – without ingredients. If we try to makeSalad() without ingredients, we’re going to end up with a literal nothing salad. This is a handy time to use UnexpectedValueException!

<?php

  function makeSalad(){
    try {
      if (getIngredients() == "Empty"){
        throw new UnexpectedValueException("Cabinet is empty");
      } catch (UnexpectedValueException $e){
        die ("Can't make a salad without ingredients. Time to goShopping()!");
      }
    }    

    $ingredients = getIngredients();
    $salad = combineIngredients($ingredients);

    return $salad;
  }
    
    makeSalad();

?>

Now, when we attempt to makeSalad(), but have no ingredients, we’ll be notified that we need more ingredients, and it’s time to go shopping! This way, we don’t waste our time, or our customers time, making a nothing salad.

Crisis averted! UnexpectedValueException is the best way to deal with potential gaps in functions, and prevent wasted time spent using values that aren’t going to work. Yet another tip for you to use on your quest for php exception handling perfection. To take it a step further, check out Airbrake’s PHP bug tracker!

Monitor Your App Free for 30 Days

Discover the power of Airbrake by starting a free 30-day trial of Airbrake. Quick sign-up, no credit card required. Get started.