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;
}
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!
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments