hoythan
V2EX  ›  PHP

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

  •  
  •   hoythan ·
    PRO
    · Jul 5, 2017 · 2885 views
    This topic created in 3409 days ago, the information mentioned may be changed or developed.
    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 replies  •  2017-07-05 15:58:49 +08:00
    hoythan
    hoythan
    OP
    PRO
    Jul 5, 2017
    1
    已经解决,原来是习惯性的漏了\
    ```
    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
    ljmready
    Jul 5, 2017❤️1
    2
    命名空间中要加\
    Mitt
    Mitt
    Jul 5, 2017❤️1
    3
    是时候换个 IDE 了 比如 JetBrians 全家桶
    About   ·   Help   ·   Advertise   ·   Blog   ·   API   ·   FAQ   ·   Privacy   ·   Solana   ·   1413 Online   Highest 6679   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 30ms · UTC 18:49 · PVG 02:49 · LAX 10:49 · JFK 13:49
    ♥ Do have faith in what you're doing.