Detailed Explanation of PHP Exception Class and Exception Handling Operation Example

  • 2021-11-13 00:58:59
  • OfStack

In this paper, the PHP exception class and exception handling operation are described as examples. Share it for your reference, as follows:

Exception handling is classified as error handling, and PHP added the Exception exception handling class from 5.1. 0.

1. Exception handling

PHP exception handling is similar to Java, using try, throw, catch statements, and the code when an exception occurs. If the exception is not caught and is not used set_exception_handler() If handled accordingly, a serious error (fatal error) will occur and an error message "Uncaught Exception" (exception not caught) will be output.

1. try:

For code blocks where exceptions may occur.

2. throw:

Specifies how to fire (trigger) exceptions for throwing exceptions. Every throw must correspond to at least 1 catch.

3. catch:

Catch exceptions and create objects that contain exception information.

Note: Let's just think that the exception of php must be caught by throw.

Basic structure:


try{
#some codes
throw new Exception("message"[,code[,...]]);
}
catch(Exception $ex){
#some codes
}

2. PHP Exception Base Class Exception

Class Summary:


Exception {
/*  Attribute  */
protected string $message ;
protected int $code ;
protected string $file ;
protected int $line ;
/*  Method  */
public __construct ([ string $message = "" [, int $code = 0 [, Exception $previous = NULL ]]] )
final public string getMessage ( void )
final public Exception getPrevious ( void )  // Gets the first in the exception chain 1 Anomalies 
final public int getCode ( void )
final public string getFile ( void )
final public int getLine ( void )
final public array getTrace ( void )   // Get exception tracking information 
final public string getTraceAsString ( void )  // Returns exception tracking information as a string 
public string __toString ( void )
final private void __clone ( void )
}

Description:

It can be seen from this base class that the php exception object mainly contains the text information of the exception (message), the exception code/code (code, which should be used for developer identification), the file where the exception occurred (file, that is, the php file where the exception occurred), and the specific location where the exception occurred (line, the line number where the exception was thrown).

Example:


<?php
try {
 throw new Exception("Some error message", 30);// Throw an exception and set the exception code to 30
} catch(Exception $e) {
 echo "Exception:file:".$e->getFile().",message:" . $e->getMessage().",code:".$e->getCode()."line:".$e->getLine();
}
?>

Browser print results:

Exception:file:D:\studyFolder\wamp\workspace\basicphp\testException.php,message:Some error message,code:30line:3

For the basics of classes and objects in php (such as method invocation), see the Class and Object section for details.

3. Custom exception classes

Example:


class customException extends Exception
 {
 public function errorMessage()
 {
 //error message
 $errorMsg = 'Error on line '.$this->getLine().' in '.$this->getFile()
 .': <b>'.$this->getMessage().'</b> is not a valid E-Mail address';
 return $errorMsg;
 }
 }

Throw and catch the exception:


try{
throw new customException(" This is a custom exception. ");
}
catch(customException $ex){
#some codes
}

4. Multiple catch catch exceptions

When one try statement may throw different exceptions, the corresponding catch blocks may catch different types of exceptions. Same as one note in java:

1. Put the big abnormal catch behind. Because when throwing exceptions, which catch is satisfied first is judged in sequence, only one catch is executed at a time.

2. Execute try once, and execute at most one catch (when an exception occurs), that is, if the previous catch meets the execution, the subsequent catch will not be considered. (Common test questions)

5. Nested Throw Exceptions

Structure example:


try{
 try{
  throw new Exception(" No. 1 1 Anomalies ");
 }
 catch(Exception $e1){
  # Correlation processing 
  throw new Exception(" Throw an exception after processing ");// Throw the exception again 
 }
}
catch(Exception $e2){
 # Correlation processing 
}

6. Set up a top-level exception handler

set_exception_handler('myException') Function sets the handler (function name, here myException) for all uncaught exceptions.

Example:


<?php
function myException($exception)
{
echo "<b>Exception:</b> " , $exception->getMessage();
}
set_exception_handler('myException');
throw new Exception('Uncaught Exception occurred');
?>

Results:

Exception: Uncaught Exception occurred

For more readers interested in PHP related content, please check the topics on this site: "Summary of PHP Error and Exception Handling Methods", "Summary of php String (string) Usage", "Encyclopedia of PHP Array (Array) Operation Skills", "Introduction to PHP Basic Syntax", "Introduction to php Object-Oriented Programming", "Introduction to php+mysql Database Operation Skills" and "Summary of php Common Database Operation Skills"

I hope this article is helpful to everyone's PHP programming.


Related articles: