Throwing exceptions in a PHP Try Catch block Throwing exceptions in a PHP Try Catch block php php

Throwing exceptions in a PHP Try Catch block


function _modulename_getData($field, $table) {  try {    if (empty($field)) {      throw new Exception("The field is undefined.");     }    // rest of code here...  }  catch (Exception $e) {    /*        Here you can either echo the exception message like:         echo $e->getMessage();         Or you can throw the Exception Object $e like:        throw $e;    */  }}


Just remove the throw from the catch block — change it to an echo or otherwise handle the error.

It's not telling you that objects can only be thrown in the catch block, it's telling you that only objects can be thrown, and the location of the error is in the catch block — there is a difference.

In the catch block you are trying to throw something you just caught — which in this context makes little sense anyway — and the thing you are trying to throw is a string.

A real-world analogy of what you are doing is catching a ball, then trying to throw just the manufacturer's logo somewhere else. You can only throw a whole object, not a property of the object.