本文介绍了在PHP中重新引发异常会破坏堆栈跟踪吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在C#中,执行以下操作将破坏异常的堆栈跟踪:

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;
}

因此,首选使用 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.

但是,使用 throw; 而不指定异常对象是PHP中的无效语法.这个问题在PHP中根本不存在吗?如下使用throw $ e不会破坏堆栈跟踪吗?

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;
}

推荐答案

像在PHP中一样抛出$ e时,您将重新抛出现有的异常对象而不更改其内容,并发送所有给定的信息,包括捕获到的堆栈跟踪信息异常-因此您的第二个示例是在PHP中重新引发异常的正确方法.

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() );

请注意,这不仅会丢失堆栈跟踪,还会丢失异常对象中可能包含的除消息以外的所有其他信息(例如, Code File Line 表示 RuntimeException ).因此,通常 不推荐

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!

这篇关于在PHP中重新引发异常会破坏堆栈跟踪吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-06 09:04