Friday, 25 July 2008

PHP Exceptions - getLine() vs. getTrace()['line']

The getLine() method called on an exception object returns information that differs from the ['line'] entry in the array returned by getTrace().

Using a trivial example (and the bad practice of dumping output to the screen), the following code..........

<?php
 
class exceptionContents
{
public function display()
{
try
{
$exception = new Exception('test exception message', 8);
throw $exception;
}
catch(Exception $exception)
{
echo '$exception->getCode() = '.$exception->getCode().'<br />';
echo '$exception->getFile() = '.$exception->getFile().'<br />';
echo '$exception->getLine() = '.$exception->getLine().'<br />';
echo '$exception->getMessage() = '.$exception->getMessage().'<br /><br />';
echo 'var_dump($exception->getTrace()) = ';
echo var_dump($exception->getTrace()).'<br />'.'<br />';
echo '$exception->getTraceAsString() = '.'<br />'.$exception->getTraceAsString().'<br />';
}
 
}
}
 
$exceptionContents = new ExceptionContents();
$exceptionContents->display();
 
?>


.......returns this sort of output.....


$exception->getCode() = 8
$exception->getFile() = /path/to/phpFile.php
$exception->getLine() = 9
$exception->getMessage() = test exception message

var_dump($exception->getTrace()) =
array
0 =>
array
'file' => string '/path/to/phpFile.php' (length=57)
'line' => int 27
'function' => string 'display' (length=7)
'class' => string 'exceptionContents' (length=17)
'type' => string '->' (length=2)
'args' =>
array
empty


$exception->getTraceAsString() =
#0 /path/to/phpFile.php(27): exceptionContents->display()
#1 {main}



$exception->getLine()
  • returns the line number on which the Exception was created (line 9 in this example).


$exception->getTrace()
$exceptionTrace = $exception->getTrace();
$exceptionTrace[0]['line'];

  • returns the line number for the method/function call that resulted in an exception being thrown (line 27 in this example).


By the same token, $exception->getFile() and $exception->getTrace['file'] also differ and if, for instance, a static method call is made and this call results in an exception being thrown, then getFile() will list the file in which the exception was created and thrown, whereas getTrace()['file'] will list the file in which the static method call was made.

No comments: