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 an exception is thrown, the code following it will not be executed, and PHP will try to find the matching "catch" block. If an exception is not caught, a fatal error will be issued with an "Uncaught Exception" message.
The throw statement throws a user-defined exception. Execution of the current function will stop (the statements after throw won't be executed), and control will be passed to the first catch block in the call stack. If no catch block exists among caller functions, the program will terminate.
But, what is a stack trace? In essence, it is a rundown of every file and function that is called leading up to the error. To be clear, a stack trace doesn't include the files and functions that are touched before the error occurred, only the chain of methods that are called as the error happened.
Re-throwing Exceptions When an exception is caught, we can perform some operations, like logging the error, and then re-throw the exception. Re-throwing an exception means calling the throw statement without an exception object, inside a catch block. It can only be used inside a catch block.
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!
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With