Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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));
like image 893
dreftymac Avatar asked Jul 06 '09 14:07

dreftymac


People also ask

Does multiple catch blocks can be used for a single try in PHP?

The throw is a keyword that is used to throw an exception. Each try block must have at least one catch block. On the other hand, a try block can also have multiple catch blocks to handle various classes of exception.

How does try catch work in PHP?

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.

How do you handle exceptions in PHP?

An exception can be thrown, and caught ("catched") within PHP. Code may be surrounded in a try block. Each try must have at least one corresponding catch block. Multiple catch blocks can be used to catch different classes of exceptions.


2 Answers

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.

like image 194
Matt Bridges Avatar answered Sep 21 '22 04:09

Matt Bridges


A warning will always be produced by the code you provided but you can use set_error_handler to dictate how the warning is handled; i.e. you can cause it to throw an exception. Furthermore, you can use restore_error_handler to return to default error handling when your done.

function errorHandler($errno, $errstr, $errfile, $errline) {
    throw new Exception($errstr, $errno);
}
set_error_handler('errorHandler');
like image 34
Lawrence Barsanti Avatar answered Sep 23 '22 04:09

Lawrence Barsanti