V2EX = way to explore
V2EX 是一个关于分享和探索的地方
现在注册
已注册用户请  登录
hoythan
V2EX  ›  PHP

PHP 在类中无法使用 try{...}catch{...}

  •  
  •   hoythan · 2017-07-05 11:51:23 +08:00 · 1881 次点击
    这是一个创建于 2498 天前的主题,其中的信息可能已经有所发展或是发生改变。
    try {
    	throw new \Exception('gateway.empty-gateway', 404);
    } catch (Exception $e){
    	print_r($e);
    }
    

    如上面的代码,如果我直接使用的话,是可以 print_r($e);出内容来的 但是如果我放到自己定义的类中比如

    namespace xxx
    class test
    {
    	public function run ()
        {
            try {
                throw new \Exception('gateway.empty-gateway', 404);
            } catch (Exception $e){
                print_r($e);
            }
        }
    }
    

    这样就不行了,会直接打印出报错

    Fatal error: Uncaught Exception: gateway.empty-gateway  ...
    
    3 条回复    2017-07-05 15:58:49 +08:00
    hoythan
        1
    hoythan  
    OP
       2017-07-05 11:52:58 +08:00
    已经解决,原来是习惯性的漏了\
    ```
    namespace xxx
    class test
    {
    public function run ()
    {
    try {
    throw new \Exception('gateway.empty-gateway', 404);
    } catch (Exception $e){
    print_r($e);
    }
    }
    }
    ```
    改为
    ```
    namespace xxx
    class test
    {
    public function run ()
    {
    try {
    throw new \Exception('gateway.empty-gateway', 404);
    } catch (\Exception $e){
    print_r($e);
    }
    }
    }
    ```

    ```
    ...
    } catch (\Exception $e){
    ...
    ```
    添加一个 \
    ljmready
        2
    ljmready  
       2017-07-05 11:54:46 +08:00   ❤️ 1
    命名空间中要加\
    Mitt
        3
    Mitt  
       2017-07-05 15:58:49 +08:00   ❤️ 1
    是时候换个 IDE 了 比如 JetBrians 全家桶
    关于   ·   帮助文档   ·   博客   ·   API   ·   FAQ   ·   我们的愿景   ·   实用小工具   ·   1001 人在线   最高记录 6543   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 25ms · UTC 21:38 · PVG 05:38 · LAX 14:38 · JFK 17:38
    Developed with CodeLauncher
    ♥ Do have faith in what you're doing.