首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >PHP:\命名空间内的Exception或Exception

PHP:\命名空间内的Exception或Exception
EN

Stack Overflow用户
提问于 2016-10-16 05:06:14
回答 2查看 13K关注 0票数 8

我正在尝试处理api中的一些错误。然而,我尝试了这么多方法来执行它所需要做的事情?

在代码中,我使用了Exception,\Exception,另一个扩展为Exception的类"use \Exception“。这些选项都不起作用。我需要做什么来执行块捕获?

代码语言:javascript
复制
  //Piece of source in the begin of file
    namespace Business\Notifiers\Webhook;
    use \Exception;
    class MyException extends \Exception {}

    //Piece of source from my class
    try{

        $products = $payment->getProducts();
        if(count($products) == 0)
            return;
        $flight_id = $products[0]->flight_id;
        $this->message = 'Sir, we have a new request: ';
        $products = null; //Chagind it to null to force an error..
        foreach($products as $product){

            $this->appendAttachment(array(
                'color' => '#432789',
                'text' => 
                    "*Name:* $product->name $product->last_name \n" . 
                    "*Total Paid:*  R\$$product->price\n",
                'mrkdwn_in' => ['text', 'pretext']
            ));
        }
    } catch(Exception $e){
        $this->message = "A exception occurred ";
    } catch(\Exception $e){
        $this->message = "A exception occurred e";
    } catch(MyException $e){
        $this->message = "A exception occurred";
    } 
EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2016-10-16 05:32:44

首先,您需要了解异常和错误之间的区别:

  1. http://php.net/manual/en/language.exceptions.php
  2. http://php.net/manual/en/ref.errorfunc.php

尝试对空值进行foreach操作不会产生异常,但会触发错误。您可以使用错误处理程序将错误包装在异常中,如下所示:

代码语言:javascript
复制
<?php

function handle ($code, $message)
{
    throw new \Exception($message, $code);
}

set_error_handler('handle');

// now this will fail
try {
    $foo = null;
    foreach ($foo as $bar) {
    }
} catch(\Exception $e) {
    echo $e->getMessage();
}

但是,在您的代码中,您可以简单地检查$products是否为空,如果是,则抛出异常:

代码语言:javascript
复制
if (!$products) {
    throw new \Exception('Could not find any products')
}
foreach($products as $product) { ...
票数 4
EN

Stack Overflow用户

发布于 2019-09-12 10:25:53

上面接受的答案给出了问题的真正原因,但没有回答主题

如果有人对此感兴趣并正在寻找

命名空间内的Exception和\Exception有什么区别?

对于PHP 7.3.5仍然有效:

  1. \ Exception : Refer in root Exception Refer in current namespace
  2. PHP does Refer to root namespace,如果在当前名称空间中找不到类,它将发出错误。

代码语言:javascript
复制
<?php
namespace Business;
try {
    throw new Exception("X"); //  Uncaught Error: Class 'Business\Exception' not found
} catch (Exception $e) {
    echo "Exception: " . $e->getMessage();
}

代码语言:javascript
复制
<?php
namespace Business;
class Exception extends \Exception {} // means \Business\Exception extends \Exception

$a = new Exception('hi'); // $a is an object of class \Business\Exception
$b = new \Exception('hi'); // $b is an object of class \Exception
票数 17
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/40064204

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档