Php exception previous exception

PHP Exceptions

An exception is an object that describes an error or unexpected behaviour of a PHP script.

Exceptions are thrown by many PHP functions and classes.

User defined functions and classes can also throw exceptions.

Exceptions are a good way to stop a function when it comes across data that it cannot use.

Throwing an Exception

The throw statement allows a user defined function or method to throw an exception. When an exception is thrown, the code following it will not be executed.

If an exception is not caught, a fatal error will occur with an «Uncaught Exception» message.

Lets try to throw an exception without catching it:

Example

function divide($dividend, $divisor) if($divisor == 0) throw new Exception(«Division by zero»);
>
return $dividend / $divisor;
>

The result will look something like this:

Fatal error: Uncaught Exception: Division by zero in C:\webfolder\test.php:4
Stack trace: #0 C:\webfolder\test.php(9):
divide(5, 0) #1 thrown in C:\webfolder\test.php on line 4

The try. catch Statement

To avoid the error from the example above, we can use the try. catch statement to catch exceptions and continue the process.

Syntax

Example

Show a message when an exception is thrown:

function divide($dividend, $divisor) if($divisor == 0) throw new Exception(«Division by zero»);
>
return $dividend / $divisor;
>

try echo divide(5, 0);
> catch(Exception $e) echo «Unable to divide.»;
>
?>

The catch block indicates what type of exception should be caught and the name of the variable which can be used to access the exception. In the example above, the type of exception is Exception and the variable name is $e .

The try. catch. finally Statement

The try. catch. finally statement can be used to catch exceptions. Code in the finally block will always run regardless of whether an exception was caught. If finally is present, the catch block is optional.

Syntax

try <
code that can throw exceptions
> catch(Exception $e) <
code that runs when an exception is caught
> finally <
code that always runs regardless of whether an exception was caught
>

Читайте также:  Java read properties file from resources

Example

Show a message when an exception is thrown and then indicate that the process has ended:

function divide($dividend, $divisor) if($divisor == 0) throw new Exception(«Division by zero»);
>
return $dividend / $divisor;
>

try echo divide(5, 0);
> catch(Exception $e) echo «Unable to divide. «;
> finally echo «Process complete.»;
>
?>

Example

Output a string even if an exception was not caught:

function divide($dividend, $divisor) if($divisor == 0) throw new Exception(«Division by zero»);
>
return $dividend / $divisor;
>

try echo divide(5, 0);
> finally echo «Process complete.»;
>
?>

The Exception Object

The Exception Object contains information about the error or unexpected behaviour that the function encountered.

Syntax

Parameter Values

Parameter Description
message Optional. A string describing why the exception was thrown
code Optional. An integer that can be used used to easily distinguish this exception from others of the same type
previous Optional. If this exception was thrown in a catch block of another exception, it is recommended to pass that exception into this parameter

Methods

When catching an exception, the following table shows some of the methods that can be used to get information about the exception:

Method Description
getMessage() Returns a string describing why the exception was thrown
getPrevious() If this exception was triggered by another one, this method returns the previous exception. If not, then it returns null
getCode() Returns the exception code
getFile() Returns the full path of the file in which the exception was thrown
getLine() Returns the line number of the line of code which threw the exception

Example

Output information about an exception that was thrown:

function divide($dividend, $divisor) if($divisor == 0) throw new Exception(«Division by zero», 1);
>
return $dividend / $divisor;
>

try echo divide(5, 0);
> catch(Exception $ex) $code = $ex->getCode();
$message = $ex->getMessage();
$file = $ex->getFile();
$line = $ex->getLine();
echo «Exception thrown in $file on line $line: [Code $code]
$message»;
>
?>

Complete Exception Reference

For a complete reference, go to our Complete PHP Exception Reference.

The reference contains descriptions and examples of all Exception methods.

Источник

Exception::getPrevious

Returns previous Throwable (which had been passed as the third parameter of Exception::__construct() ).

Parameters

This function has no parameters.

Return Values

Returns the previous Throwable if available or null otherwise.

Читайте также:  Кнопка

Examples

Example #1 Exception::getPrevious() example

Looping over, and printing out, exception trace.

class MyCustomException extends Exception <>

function doStuff () try throw new InvalidArgumentException ( «You are doing it wrong!» , 112 );
> catch( Exception $e ) throw new MyCustomException ( «Something happened» , 911 , $e );
>
>

try doStuff ();
> catch( Exception $e ) do printf ( «%s:%d %s (%d) [%s]\n» , $e -> getFile (), $e -> getLine (), $e -> getMessage (), $e -> getCode (), get_class ( $e ));
> while( $e = $e -> getPrevious ());
>
?>

The above example will output something similar to:

/home/bjori/ex.php:8 Something happened (911) [MyCustomException] /home/bjori/ex.php:6 You are doing it wrong! (112) [InvalidArgumentException]

See Also

User Contributed Notes 2 notes

/**
* Gets sequential array of all previously-chained errors
*
* @param Throwable $error
*
* @return Throwable[]
*/
function getChain(Throwable $error) : array
$chain = [];

do $chain[] = $error;
> while ($error = $error->getPrevious());

May be I am late (5.2 is not supported). But if you want use the functionality of «previous Exception» in PHP < 5.3 or write compatible code, you can use next way as below.

abstract class App_Exception_PreviousNativeAbstract extends Exception public static $printPrevious = true ;

public function __toString () $result = array();
$result [] = sprintf ( «Exception ‘%s’ with message ‘(%s) %s’ in %s:%d» , get_class ( $this ), $this -> code , $this -> message , $this -> file , $this -> line );
$result [] = ‘—[Stack trace]:’ ;
$result [] = $this -> getTraceAsString ();

if ( self :: $printPrevious ) $previous = $this -> getPrevious ();
if ( $previous ) do $result [] = ‘—[Previous exception]:’ ;
$result [] = sprintf ( «Exception ‘%s’ with message ‘(%s) %s’ in %s:%d» , get_class ( $previous ), $previous -> getCode (), $previous -> getMessage (), $previous -> getFile (), $previous -> getLine ());
$result [] = ‘—[Stack trace]:’ ;
$result [] = $previous -> getTraceAsString ();
> while( method_exists ( $previous , ‘getPrevious’ ) && ( $previous = $previous -> getPrevious ()));
>
>

return implode ( «\r\n» , $result );
>
>

abstract class App_Exception_PreviousLegacyAbstract extends App_Exception_PreviousNativeAbstract protected $previous ;

public function __construct ( $message , $code = 0 , Exception $previous = null ) $this -> previous = $previous ;

parent :: __construct ( $message , $code );
>

public function getPrevious () return $this -> previous ;
>
>

if ( version_compare ( PHP_VERSION , ‘5.3.0’ , ‘>=’ )) abstract class App_Exception_PreviousAbstract extends App_Exception_PreviousNativeAbstract <>
>
else abstract class App_Exception_PreviousAbstract extends App_Exception_PreviousLegacyAbstract <>
>

class App_Exception extends App_Exception_PreviousAbstract public function __construct ( $message , $code = 0 , Exception $previous = null ) parent :: __construct ( $message , 0 , $previous );
>
>

Читайте также:  Html dom element parent

// Example:
try // .
throw new Exception ( ‘Exception mesage’ );
// .
> catch ( Exception $e ) throw new App_Exception ( ‘App exception mesage’ , 0 , $e );
>
?>

Источник

Exception::__construct

The previous exception used for the exception chaining.

Note: Calling the constructor of class Exception from a subclass ignores the default arguments, if the properties $code and $message are already set.

Notes

Note:

The message is NOT binary safe.

User Contributed Notes 3 notes

For those that haven’t done exception chaining. Here’s an example.

This allows you to add the previous exception to the next one and give yourself detailed information in the end as to what happened. This is useful in larger applications.

function theDatabaseObj () if( database_object ) return database_object ;
>
else throw new DatabaseException ( «Could not connect to the database» );
>
>

function updateProfile ( $userInfo ) try $db = theDatabaseObj ();
$db -> updateProfile ();
>
catch( DatabaseException $e ) $message = «The user :» . $userInfo -> username . » could not update his profile information» ;
/* notice the ‘$e’. I’m adding the previous exception to this exception. I can later get a detailed view of
where the problem began. Lastly, the number ’12’ is an exception code. I can use this for categorizing my
exceptions or don’t use it at all. */
throw new MemberSettingsException ( $message , 12 , $e );
>
>

try updateProfile ( $userInfo );
>
catch( MemberSettingsException $e ) // this will give all information we have collected above.
echo $e -> getTraceAsString ();
>
?>

Be aware that while $previous is quite useful in providing exception chaining and better traceability, none of the internal php exceptions (e.g. PDOException, ReflectionException, etc) are called internally within php with $previous in mind.

So if your code throws an exception, recovers from it, then catches one of these internal php exceptions, recovers from it and throws another exception, you will not know the first exception that was thrown when calling getPrevious.

Note that the code parameter is not the same as exit($code).
Also, the code argument in PHP 7 (possibly earlier versions) is cast to an int including negative values. The code below is completely valid:

try
throw new \ Exception ( ‘Testing’ , — 12.12 );
>
catch (\ Exception $exception )
$code = $exception -> getCode ();
if ( $code < 0 )
exit( abs ( $code ));
>
>

Источник

Оцените статью