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!
When an exception is cached in a catch block, you can re-throw it using the throw keyword (which is used to throw the exception objects). Or, wrap it within a new exception and throw it.
Throw: The throw keyword is used to signal the occurrence of a PHP exception. The PHP runtime will then try to find a catch statement to handle the exception. Catch: This block of code will be called only if an exception occurs within the try code block.
The primary method of handling exceptions in PHP is the try-catch. In a nutshell, the try-catch is a code block that can be used to deal with thrown exceptions without interrupting program execution. In other words, you can "try" to execute a block of code, and "catch" any PHP exceptions that are thrown.
Yes, uncaught exceptions result in fatal errors that stop the execution of the script.
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;     */   } } 
                        If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With