Must "throw" be inside a try statement?

Hi,

I have a throw code in one of my php file which is not surrounded by the try statement like so:

File A:


function test( ) {
    if( $action ) {
        echo 1;
    }
    else {
        throw new customException( );
    }
}

File B:

include fileA.php;

try {
    test( );
}
catch( customException $e ) {
    // do something
}

Is this considered the correct way because I am stuck at this portion of code while debugging and its not showing me any error message at all. Even the error_log yields nothing.

Any help appreciated.

Hi justspree,

Throw is used when throwing an error inside a function or an Object’s method. The code that calls the function/method is wrapped in try/catch blocks ad if an error occurs inside the called function/method the catch part of the block runs and determines how you handle the error. Like:

 
function calculateFraction($value){
   if(!$value){
        throw new Exception('Cannot divide by zero.');
   } else {
       return (1/$value);
   }
}

/*call the function*/
try {
    echo calculateFraction(2);
    echo calculateFraction(0);
} catch (Exception $e){
    echo 'Caught exception: ',  $e->getMessage(), "\
";
}
/* Outputs */ 
 0.5 
 Caught exception: Cannot divide by zero.
?>

Steve

Thank you for your reply Steve. I understand that but I’m asking if is there a difference between my code and yours? Anything I’ve done wrong on mine?

Hi, your code is using it correctly. You may want to simplify the handling of the exception for the time being and not use a custom handler. See if you trigger an error then add your custom handler back to see if it is ‘eating’ your error.

Regards,
Steve

Oh ok thanks a bunch Steve! Will try it.