search
HomeBackend DevelopmentPHP TutorialPHP exception handling related knowledge

  1. //create function with an exception
  2. function checkNum($number)
  3. {
  4. if($number>1)
  5. {
  6. throw new Exception("Value must be 1 or below") ;
  7. }
  8. return true;
  9. }
  10. //trigger exception
  11. checkNum(2);
  12. ?>
Copy code

The above code will get an error like this: Fatal error: Uncaught exception 'Exception' with message 'Value must be 1 or below' in C:webfoldertest.php:6 Stack trace: #0 C:webfoldertest.php(12): checkNum(28) #1 {main} thrown in C:webfoldertest.php on line 6 Try, throw and catch To avoid the errors in the above example, we need to create appropriate code to handle exceptions.

Processing procedures should include: Try - Functions that use exceptions should be inside a "try" block. If no exception is triggered, the code continues execution as usual. But if an exception is triggered, an exception will be thrown. Throw - This specifies how to trigger the exception. Each "throw" must correspond to at least one "catch" Catch - The "catch" code block will catch the exception and create an object containing the exception information

Let’s trigger an exception:

  1. //Create a function that can throw an exception
  2. function checkNum($number)
  3. {
  4. if($number>1)
  5. {
  6. throw new Exception("Value must be 1 or below");
  7. }
  8. return true;
  9. }
  10. //Trigger exception in "try" code block
  11. try
  12. {
  13. checkNum(2);
  14. //If the exception is thrown, this text will not be shown
  15. echo 'If you see this, the number is 1 or below';
  16. }
  17. //Catch exception
  18. catch(Exception $e)
  19. {
  20. echo 'Message: ' .$e->getMessage();
  21. }
  22. ?>
Copy the code

The above code will get an error similar to this: Message: Value must be 1 or below Example explanation: The code above throws an exception and catches it: Create checkNum() function. It detects whether the number is greater than 1. If so, throw an exception. Call the checkNum() function in the "try" block. Exception in checkNum() function is thrown The "catch" code block receives the exception and creates an object ($e) containing the exception information. Output the error message from this exception by calling $e->getMessage() from this exception object

However, in order to follow the principle of "each throw must correspond to a catch", you can set up a top-level exception handler to handle missed errors. Create a custom Exception class Creating custom exception handlers is very simple. We simply created a specialized class whose functions are called when an exception occurs in PHP. This class must be an extension of the exception class.

This custom exception class inherits all properties of PHP's exception class, and you can add custom functions to it.

We start creating the exception class:

  1. class customException extends Exception
  2. {
  3. public function errorMessage()
  4. {
  5. //error message
  6. $errorMsg = 'Error on line '.$this->getLine().' in '.$this->getFile()
  7. .': '.$this->getMessage().' is not a valid E-Mail address';
  8. return $errorMsg ;
  9. }
  10. }
  11. $email = "someone@example...com";
  12. try
  13. {
  14. //check if
  15. if(filter_var($email, FILTER_VALIDATE_EMAIL) === FALSE)
  16. {
  17. // throw exception if email is not valid
  18. throw new customException($email);
  19. }
  20. }
  21. catch (customException $e)
  22. {
  23. //display custom message
  24. echo $e->errorMessage();
  25. }
  26. ?>
Copy code

This new class is a copy of the old exception class, plus the errorMessage() function. Just because it is a copy of the old class, it inherits the properties and methods from the old class, and we can use the methods of the exception class, such as getLine(), getFile(), and getMessage(). Example explanation: The above code throws an exception and catches it through a custom exception class: The customException() class was created as an extension of the old exception class. This way it inherits all properties and methods of the old class. Create errorMessage() function. If the e-mail address is not valid, this function returns an error message Set the $email variable to an illegal e-mail address string Execute the "try" code block and throw an exception because the e-mail address is invalid The "catch" code block catches the exception and displays the error message

Multiple exceptions

You can use multiple exceptions for a script to detect multiple situations.

You can use multiple if..else code blocks, or a switch code block, or nest multiple exceptions. These exceptions can use different exception classes and return different error messages:

  1. class customException extends Exception
  2. {
  3. public function errorMessage()
  4. {
  5. //error message
  6. $errorMsg = 'Error on line '.$this->getLine().' in '.$this->getFile()
  7. .': '.$this->getMessage().' is not a valid E-Mail address';
  8. return $errorMsg ;
  9. }
  10. }
  11. $email = "someone@example.com";
  12. try
  13. {
  14. //check if
  15. if(filter_var($email, FILTER_VALIDATE_EMAIL) === FALSE)
  16. {
  17. //throw exception if email is not valid
  18. throw new customException($email);
  19. }
  20. //check for "example" in mail address
  21. if(strpos($email, "example") !== FALSE)
  22. {
  23. throw new Exception ("$email is an example e-mail");
  24. }
  25. }
  26. catch (customException $e)
  27. {
  28. echo $e->errorMessage();
  29. }
  30. catch(Exception $e)
  31. {
  32. echo $e->getMessage();
  33. }
  34. ?>
Copy code

Example explanation: The above code tests two conditions. If any condition is not true, an exception is thrown: The customException() class was created as an extension of the old exception class. This way it inherits all properties and methods of the old class. Create errorMessage() function. If the e-mail address is not valid, this function returns an error message. Execute the "try" block of code, and in the first condition, no exception will be thrown. Since the e-mail contains the string "example", the second condition triggers an exception. The "catch" code block will catch the exception and display the appropriate error message

If customException is not caught and base exception is caught tightly, the exception is handled there. Rethrow the exception

Sometimes, when an exception is thrown, you may want to handle it differently than the standard way. The exception can be thrown again in a "catch" block.

The script should hide system errors from the user. System errors may be important to programmers, but users are not interested in them. To make it easier for users, you can throw the exception again with a user-friendly message:

  1. class customException extends Exception
  2. {
  3. public function errorMessage()
  4. {
  5. //error message
  6. $errorMsg = $this->getMessage().' is not a valid E- Mail address.';
  7. return $errorMsg;
  8. }
  9. }
  10. $email = "someone@example.com";
  11. try
  12. {
  13. try
  14. {
  15. //check for "example" in mail address
  16. if( strpos($email, "example") !== FALSE)
  17. {
  18. //throw exception if email is not valid
  19. throw new Exception($email);
  20. }
  21. }
  22. catch(Exception $e)
  23. {
  24. / /re-throw exception
  25. throw new customException($email);
  26. }
  27. }
  28. catch (customException $e)
  29. {
  30. //display custom message
  31. echo $e->errorMessage();
  32. }
  33. ?> ;
Copy code

Example explanation: The above code detects whether the string "example" is contained in the email address. If so, throw the exception again: The customException() class was created as an extension of the old exception class. This way it inherits all properties and methods of the old class. Create errorMessage() function. If the e-mail address is not valid, this function returns an error message. Set the $email variable to a valid email address, but containing the string "example". A "try" block contains another "try" block so that the exception can be thrown again. The exception is triggered because the e-mail contains the string "example". "catch" catches the exception and rethrows "customException". A "customException" is caught and an error message is displayed.

If the exception is not caught in its current "try" block, it will look for a catch block at a higher level.

Set the Top Level Exception Handler

The set_exception_handler() function can set a user-defined function that handles all uncaught exceptions.

  1. function myException($exception)
  2. {
  3. echo "Exception: " , $exception->getMessage();
  4. }
  5. set_exception_handler( 'myException');
  6. throw new Exception('Uncaught Exception occurred');
  7. ?>
Copy code

The output of the above code should be similar to this: Exception: Uncaught Exception occurred In the above code, there is no "catch" block, instead the top-level exception handler is triggered. This function should be used to catch all uncaught exceptions. unusual rules Code that requires exception handling should be placed within a try block to catch potential exceptions. Every try or throw block must have at least one corresponding catch block. Use multiple catch blocks to catch different kinds of exceptions. Exceptions can be re-thrown in a catch block within a try block.

In short: if an exception is thrown, you must catch it.

Source: http://bbs.it-home.org/w3school/php/php_exception.html

Example:

  1. function throwTest($data)
  2. {
  3. try
  4. {
  5. if (!is_array($data) || emptyempty($data))
  6. {
  7. throw new Exception('data The type is not an array', 445);
  8. }
  9. echo('Done for testing!!');
  10. }
  11. catch (Exception $e)
  12. {
  13. /*echo 'Error message:',$e->getMessage( ), '
    ';//Error message
  14. echo '
    Error code:', $e->getCode(), '
    ';//Error code
  15. echo '
    Error file:', $e->getFile(), '
    ';//Error file
  16. echo '
    Error line number:', $e->getLine (), '
    ';//Error line number
  17. echo '
    Error information is displayed in an array:', print_r($e->getTrace()), '
    ' ;//Error information is displayed as an array
  18. echo '
    Error information is displayed as a string:', $e->getTraceAsString(), '
    ';//Error information is displayed as a string* /
  19. echo $e->getMessage(), '
    ';//Error message
  20. echo '
    ', $e->getTraceAsString(), '
    ' ;//Error information is displayed as a string
  21. exit;
  22. }
  23. }
  24. //$data=array("111","33333"); //Normal test
  25. $data="8129233"; //Abnormal test
  26. throwTest($data);
  27. ?>
Copy code

Articles you may be interested in: Example of using php exception handling class Exception PHP5 exception handling, error throwing and callback functions, etc. Exception handling, error throwing and error callback functions in php A simple php custom exception class Learn php errors and exception settings



Statement
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
The Continued Use of PHP: Reasons for Its EnduranceThe Continued Use of PHP: Reasons for Its EnduranceApr 19, 2025 am 12:23 AM

What’s still popular is the ease of use, flexibility and a strong ecosystem. 1) Ease of use and simple syntax make it the first choice for beginners. 2) Closely integrated with web development, excellent interaction with HTTP requests and database. 3) The huge ecosystem provides a wealth of tools and libraries. 4) Active community and open source nature adapts them to new needs and technology trends.

PHP and Python: Exploring Their Similarities and DifferencesPHP and Python: Exploring Their Similarities and DifferencesApr 19, 2025 am 12:21 AM

PHP and Python are both high-level programming languages ​​that are widely used in web development, data processing and automation tasks. 1.PHP is often used to build dynamic websites and content management systems, while Python is often used to build web frameworks and data science. 2.PHP uses echo to output content, Python uses print. 3. Both support object-oriented programming, but the syntax and keywords are different. 4. PHP supports weak type conversion, while Python is more stringent. 5. PHP performance optimization includes using OPcache and asynchronous programming, while Python uses cProfile and asynchronous programming.

PHP and Python: Different Paradigms ExplainedPHP and Python: Different Paradigms ExplainedApr 18, 2025 am 12:26 AM

PHP is mainly procedural programming, but also supports object-oriented programming (OOP); Python supports a variety of paradigms, including OOP, functional and procedural programming. PHP is suitable for web development, and Python is suitable for a variety of applications such as data analysis and machine learning.

PHP and Python: A Deep Dive into Their HistoryPHP and Python: A Deep Dive into Their HistoryApr 18, 2025 am 12:25 AM

PHP originated in 1994 and was developed by RasmusLerdorf. It was originally used to track website visitors and gradually evolved into a server-side scripting language and was widely used in web development. Python was developed by Guidovan Rossum in the late 1980s and was first released in 1991. It emphasizes code readability and simplicity, and is suitable for scientific computing, data analysis and other fields.

Choosing Between PHP and Python: A GuideChoosing Between PHP and Python: A GuideApr 18, 2025 am 12:24 AM

PHP is suitable for web development and rapid prototyping, and Python is suitable for data science and machine learning. 1.PHP is used for dynamic web development, with simple syntax and suitable for rapid development. 2. Python has concise syntax, is suitable for multiple fields, and has a strong library ecosystem.

PHP and Frameworks: Modernizing the LanguagePHP and Frameworks: Modernizing the LanguageApr 18, 2025 am 12:14 AM

PHP remains important in the modernization process because it supports a large number of websites and applications and adapts to development needs through frameworks. 1.PHP7 improves performance and introduces new features. 2. Modern frameworks such as Laravel, Symfony and CodeIgniter simplify development and improve code quality. 3. Performance optimization and best practices further improve application efficiency.

PHP's Impact: Web Development and BeyondPHP's Impact: Web Development and BeyondApr 18, 2025 am 12:10 AM

PHPhassignificantlyimpactedwebdevelopmentandextendsbeyondit.1)ItpowersmajorplatformslikeWordPressandexcelsindatabaseinteractions.2)PHP'sadaptabilityallowsittoscaleforlargeapplicationsusingframeworkslikeLaravel.3)Beyondweb,PHPisusedincommand-linescrip

How does PHP type hinting work, including scalar types, return types, union types, and nullable types?How does PHP type hinting work, including scalar types, return types, union types, and nullable types?Apr 17, 2025 am 12:25 AM

PHP type prompts to improve code quality and readability. 1) Scalar type tips: Since PHP7.0, basic data types are allowed to be specified in function parameters, such as int, float, etc. 2) Return type prompt: Ensure the consistency of the function return value type. 3) Union type prompt: Since PHP8.0, multiple types are allowed to be specified in function parameters or return values. 4) Nullable type prompt: Allows to include null values ​​and handle functions that may return null values.

See all articles

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

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

MantisBT

MantisBT

Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.

Dreamweaver Mac version

Dreamweaver Mac version

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

PhpStorm Mac version

PhpStorm Mac version

The latest (2018.2.1) professional PHP integrated development tool

WebStorm Mac version

WebStorm Mac version

Useful JavaScript development tools