Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
792 views
in Technique[技术] by (71.8m points)

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

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));
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Warnings and notices are not technically exceptions in PHP. To catch an exception it has to be explicitly thrown, and many of the built-in libraries of functions do not throw exceptions (mostly because they were written before PHP supported exceptions).

It would have been nice if somehow exceptions were built on top of the existing notice/warning/error framework but perhaps that is asking too much.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...