try { // code that may cause an exception } catch(Exception $e) { $stacktrace = $e->getTrace(); print_r($stacktrace); }
function divide($numerator, $denominator) { if($denominator == 0) { throw new Exception("Divide by zero"); } return $numerator / $denominator; } try { echo divide(10, 0); } catch(Exception $e) { $stacktrace = $e->getTrace(); print_r($stacktrace); }This example defines a function called divide() that divides two numbers and throws an exception if the denominator is zero. It then calls the function with a denominator of zero inside a try-catch block. If an exception is thrown, the stack trace is retrieved and printed using print_r(). This can be useful for debugging issues in the code where the exception was thrown. The getTrace() function is a part of the PHP core library and does not belong to any specific package or library.