PHP try-catch 块:它们是否能够捕获无效的 arg 类型? [英] PHP try-catch blocks: are they able to catch invalid arg types?

查看:40
本文介绍了PHP try-catch 块:它们是否能够捕获无效的 arg 类型?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

背景:假设我有以下明显不正确的 PHP:

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

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

为了与 array_pop 一起工作,$vtest 显然应该是一个数组,而不是一个字符串.尽管如此,当我运行此代码时,会显示警告.我不想那样,我只想让代码默默地失败.

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.

问题:与其他语言相比,PHP try-catch 是否有什么特别之处导致它不起作用?

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

免责声明:仅供参考,在 PHP 中确实有其他方法可以处理这种情况,但这些都是不可取的.这里的目标是避免:

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:

at-sign"技巧:

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

类型转换:

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

推荐答案

警告和通知在 PHP 中并不是技术上的例外.要捕获异常,必须显式抛出异常,而且许多内置函数库都不会抛出异常(主要是因为它们是在 PHP 支持异常之前编写的).

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.

这篇关于PHP try-catch 块:它们是否能够捕获无效的 arg 类型?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆