Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Throwing exceptions in a PHP Try Catch block

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!

like image 272
kaspnord Avatar asked Jan 27 '12 22:01

kaspnord


People also ask

Can exceptions be thrown from catch block?

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.

What is throw exception PHP?

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.

Does PHP have try-catch?

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.

Does try-catch stop execution PHP?

Yes, uncaught exceptions result in fatal errors that stop the execution of the script.


Video Answer


1 Answers

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;     */   } } 
like image 191
AlienWebguy Avatar answered Oct 04 '22 23:10

AlienWebguy