Does re-throwing an exception in PHP destroy the stack trace?

喜夏-厌秋 提交于 2021-02-04 17:35:07

问题


In C#, doing the following would destroy the stack trace of an exception:

try{
    throw new RuntimeException();
}
catch(Exception e){
    //Log error

    //Re-throw
    throw e;
}

Because of this, using throw rather than throw e is preferred. This will let the same exception propagate upwards, instead of wrapping it in a new one.

However, using throw; without specifying the exception object is invalid syntax in PHP. Does this problem simply not exist in PHP? Will using throw $e as follows not destroy the stack trace?

<?php

try{
    throw new RuntimeException();
}
catch(Exception $e){
    //Log error

    //Re-throw
    throw $e;
}

回答1:


When you throw $e in PHP like you did you rethrow the exisiting exception object without changing anything of its contents and send all given information including the stacktrace of the catched exception - so your second example is the correct way to rethrow an exception in PHP.

If (for whatever reason) you want to throw the new position with the last message, you have to rethrow a newly created exception object:

throw new RuntimeException( $e->getMessage() );

Note that this will not only lose the stack trace, but also all other information which may be contained in the exception object except for the message (e.g. Code, File and Line for RuntimeException). So this is generally not recommended!




回答2:


Re-throwing the same exception will not destroy the stack trace. But depending on what you need, you might want to just throw the same exception or build an Exception Chaining ( see PHP Documentation > Exception::__construct )

A very good explanation of when and why one would choose one approach over another is given in this answer




回答3:


Yes.This is a best way to catch the exception and re-throw the same exception object which carries the stack-trace data. Once you reaches the point of method that handles requests, just catch it there and send response back to user accordingly.

Its a bad idea to throw a new exception object which looses the stack-trace and create an additional object causing memory load.

Hope this helps.



来源:https://stackoverflow.com/questions/34923644/does-re-throwing-an-exception-in-php-destroy-the-stack-trace

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!