Home Backend Development PHP Tutorial PHP5 exception handling, error throwing and callback functions, etc.

PHP5 exception handling, error throwing and callback functions, etc.

Jul 25, 2016 am 09:10 AM

  1. error_reporting(E_ALL&~E_NOTICE); // In addition to E_NOTICE, other exceptions will be triggered (the binary operation result of E_ALL&~E_NOTICE is: the value of the corresponding bit of E_NOTICE is set to 0) try-catch cannot be automatically loaded in the class Valid within function __autoload().
  2. try-catch cannot be used to catch exceptions and errors, such as errors triggered by trigger_error(). Exceptions and errors are different.
  3. try{
  4. // you codes that maybe cause an error
  5. }catch(Exception $err){ // This error object needs to declare the type, Exception is the system default exception handling class
  6. echo $err->getMessage();
  7. }
Copy code

//thrown can throw an exception, such as: thrown new Exception('an error'); one example:

  1. try {
  2. if ( empty( $var1 ) ) throw new NotEmptyException();
  3. if ( empty( $var2 ) ) throw new NotEmptyException();
  4. if ( ! preg_match() ) throw new InvalidInputException( );
  5. $model->write();
  6. $template->render( 'success' );
  7. } catch ( NotEmptyException $e ) {
  8. $template->render( 'error_empty' );
  9. } catch (InvalidInputException $e) {
  10. $template->render( 'error_preg' );
  11. }
Copy code

Exception class structure: most of the methods are prohibited from being overridden (final)

  1. Exception {
  2. /* attribute*/
  3. protected string $message ;
  4. protected int $code ;
  5. protected string $file ;
  6. protected int $line ;
  7. /* method*/
  8. public __construct ([ string $message = "" [, int $code = 0 [, Exception $previous = null]]] )
  9. final public string getMessage ( void ) //The message thrown by the exception
  10. final public Exception getPrevious ( void ) //Previous Exception
  11. final public int getCode (void) //Exception code, this is user-defined
  12. final public string getFile (void) //The file path where the exception occurred
  13. final public int getLine (void) //The line where the exception occurred
  14. final public array getTrace (void) //Exception tracking information (array)
  15. final public string getTraceAsString (void) //Exception tracking information (string)
  16. public string __toString (void) //Trying to treat the exception object directly as a string The return value of calling the sub-function when used
  17. final private void __clone (void) //Called when cloning the exception object
  18. }
Copy code

Extended exception class try-catch can have multiple catch clauses. Starting from the first catch clause, if the exception variable type in the clause matches the exception type thrown by the throw statement, the clause will be executed and no other catch clauses will be executed. clause, otherwise continue to try the next catch clause. Since Exception is the base class of all exception classes, the exceptions thrown will match it. If you use different processing methods according to different exception types, you should use Exception type The catch clause goes last. Exception is the base class of all exceptions. You can extend the exception class according to actual needs.

  1. calss MyException extends Exception{
  2. public errType = 'default';
  3. public function __construct($errType=''){
  4. $this->errType = $errType;
  5. }
  6. }
  7. thrown new MyException (); //Throw an exception
  8. try{
  9. // you codes that maybe cause an error
  10. }catch(MyException $err){ // This error object needs to declare the type
  11. echo $err->errType();
  12. }catch(ErrorException $err){ //ErrorException is an exception class added in PHP 5, inherited from Exception
  13. echo 'error !';
  14. }catch(Exception $err){
  15. redirect('/error.php');
  16. }
Copy code

You may determine the type of exception in the catch clause, or decide whether to handle the exception based on code and other information. If the code you unload the catch clause cannot properly handle the caught exception, you can continue to throw it within the catch clause. Exception occurred.

3. Exception callback function set_exception_handler(callback functionName) //This function will be called when an exception of Exception or its subclass occurs function exceptionHandlerFun($errObj){ // Exception exception callback function has only one parameter, which is the thrown exception object. //....... }

Exception exception callback function cannot eliminate the exception by returning true like set_error_handler's callback function. Even if the callback function handles the exception, subsequent code will not continue to be executed, so if you want to continue executing subsequent code, try-catch must be used . But there is an exception: the script end callback function can be executed, and the callback function can be executed even if the thrown exception is not handled. register_shutdown_function(callback functionName[,argument1,argument2,...]); For example:

  1. function shutdownfunction(){

  2. echo 'script is end';
  3. }

  4. register_shutdown_function("shutdownfunction");

Copy code

Because shutdownfunction() is executed at the end of the script, this callback function can call a function anywhere in the script, even if the function is defined after the error is thrown (the function definition is in the script Completed during compilation).

4. trigger_error(string errorMsg[,int user_error_type]) This function is used to actively trigger an error: user_error_type can only be the value of E_ALL, E_USER_ERROR, E_USER_WARNING, E_USER_NOTICE or a combination thereof. set_error_handler(callbeck functionName[,user_error_type]); //Set a callback function for trigger_error() to handle errors, including errors thrown by the system and errors triggered by the user using the trigger_error() function.

Optional parameter user_error_type: If this parameter is set, the callback function can be triggered only when the error type thrown by trigger_error matches the definition range of user_error_type. This value is set similarly to the error_reporting() function.

First parameter (callbeck functionName): A function name. The function can have 5 parameters, of which the first 2 are required, in order: The user_error_type that trigger_error throws, the errorMsg that trigger_error throws, the absolute path of the file that throws the error, the line number that throws the error, and the context when the error is thrown (an array that contains everything in the scope where trigger_error() is located. variables, functions, classes and other data) Return value of the callback function: If false is returned, the system error handling mechanism will continue to throw the error, and return true or no return value to eliminate the error. Errors triggered by trigger_error() will not be caught by try-catch exception catching statements.



Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
WWE 2K25: How To Unlock Everything In MyRise
1 months ago By 尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Explain JSON Web Tokens (JWT) and their use case in PHP APIs. Explain JSON Web Tokens (JWT) and their use case in PHP APIs. Apr 05, 2025 am 12:04 AM

JWT is an open standard based on JSON, used to securely transmit information between parties, mainly for identity authentication and information exchange. 1. JWT consists of three parts: Header, Payload and Signature. 2. The working principle of JWT includes three steps: generating JWT, verifying JWT and parsing Payload. 3. When using JWT for authentication in PHP, JWT can be generated and verified, and user role and permission information can be included in advanced usage. 4. Common errors include signature verification failure, token expiration, and payload oversized. Debugging skills include using debugging tools and logging. 5. Performance optimization and best practices include using appropriate signature algorithms, setting validity periods reasonably,

Explain the concept of late static binding in PHP. Explain the concept of late static binding in PHP. Mar 21, 2025 pm 01:33 PM

Article discusses late static binding (LSB) in PHP, introduced in PHP 5.3, allowing runtime resolution of static method calls for more flexible inheritance.Main issue: LSB vs. traditional polymorphism; LSB's practical applications and potential perfo

Framework Security Features: Protecting against vulnerabilities. Framework Security Features: Protecting against vulnerabilities. Mar 28, 2025 pm 05:11 PM

Article discusses essential security features in frameworks to protect against vulnerabilities, including input validation, authentication, and regular updates.

Customizing/Extending Frameworks: How to add custom functionality. Customizing/Extending Frameworks: How to add custom functionality. Mar 28, 2025 pm 05:12 PM

The article discusses adding custom functionality to frameworks, focusing on understanding architecture, identifying extension points, and best practices for integration and debugging.

How to send a POST request containing JSON data using PHP's cURL library? How to send a POST request containing JSON data using PHP's cURL library? Apr 01, 2025 pm 03:12 PM

Sending JSON data using PHP's cURL library In PHP development, it is often necessary to interact with external APIs. One of the common ways is to use cURL library to send POST�...

What exactly is the non-blocking feature of ReactPHP? How to handle its blocking I/O operations? What exactly is the non-blocking feature of ReactPHP? How to handle its blocking I/O operations? Apr 01, 2025 pm 03:09 PM

An official introduction to the non-blocking feature of ReactPHP in-depth interpretation of ReactPHP's non-blocking feature has aroused many developers' questions: "ReactPHPisnon-blockingbydefault...

Describe the SOLID principles and how they apply to PHP development. Describe the SOLID principles and how they apply to PHP development. Apr 03, 2025 am 12:04 AM

The application of SOLID principle in PHP development includes: 1. Single responsibility principle (SRP): Each class is responsible for only one function. 2. Open and close principle (OCP): Changes are achieved through extension rather than modification. 3. Lisch's Substitution Principle (LSP): Subclasses can replace base classes without affecting program accuracy. 4. Interface isolation principle (ISP): Use fine-grained interfaces to avoid dependencies and unused methods. 5. Dependency inversion principle (DIP): High and low-level modules rely on abstraction and are implemented through dependency injection.

See all articles