Alex Rivera | Logout

PHP try-catch blocks: are they able to catch invalid arg types?

Asked 2009-07-06T14:44:51.177
15

Background: Suppose I have the following obviously-incorrect PHP:

    try{
        $vtest = '';
        print(array_pop($vtest));
    }catch(Exception $exx){}

For it to work with array_pop, $vtest should obviously be an array, not a string. Nevertheless, when I run this code the Warning is exhibited. I don't want that, I just want the code to fail silently.

Question: Is there something special about PHP try-catch compared to other languages that cause this not to work?

Disclaimer: Just for reference, it is true there are other ways to handle this situation in PHP, but these are undesirable. The goal here is to avoid:

The "at-sign" trick:

        $vtest = '';
        print(@array_pop($vtest)); // <-- would like to avoid this

Type Casting:

        $vtest = '';
        $vtest = (array)$vtest;  
        print(array_pop($vtest));
Edit
Report

1 Answer

0

The only way I can think of would be to do the following:

$vtest = '';
try{
    if(!is_array($vtest)){
        throw new NotArrayException();
    } 
    print(array_pop($vtest));
}catch(NotArrayException $exx){}

Of course if you just want to do this silently you could just do the following since you don't need to catch any exception:

    $vtest = '';
    if(is_array($vtest)){
        print(array_pop($vtest));
    }
answered 2009-07-06T14:49:27.410

Your Answer