Throwing exceptions in a PHP Try Catch block
PhpException HandlingDrupal 6Try CatchPhp Problem Overview
I have a PHP function in a Drupal 6 .module file. I am attempting to run initial variable validations prior to executing more intensive tasks (such as database queries). In C#, I used to implement IF statements at the beginning of my Try block that threw new exceptions if a validation failed. The thrown exception would be caught in the Catch block. The following is my PHP code:
function _modulename_getData($field, $table) {
try {
if (empty($field)) {
throw new Exception("The field is undefined.");
}
// rest of code here...
}
catch (Exception $e) {
throw $e->getMessage();
}
}
However, when I try to run the code, it's telling me that objects can only be thrown within the Catch block.
Thanks in advance!
Php Solutions
Solution 1 - Php
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;
*/
}
}
Solution 2 - Php
To rethrow do
throw $e;
not the message.
Solution 3 - Php
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.
Solution 4 - Php
You tried to throw a string
:
throw $e->getMessage();
You can only throw objects that implement \Throwable
, e.g. \Exception
.
As a sidenote: Exceptions are usually to define exceptional states of the application and not for error messages after validation. Its not an exception, when a user gives you invalid data
Solution 5 - Php
Throw needs an object instantiated by \Exception
. Just the $e
catched can play the trick.
throw $e