Get the App
SLTechnology News&Howtos  ›  Development  › 

How to implement exception handling in php

Shulou Source: shulou.com Published: 2022-06-01 13:10:46 09月16日 Update

This article will explain in detail how to achieve exception handling in php. The editor thinks it is very practical, so I share it with you as a reference. I hope you can get something after reading this article.

Detailed explanation of php exception handling

Function: centralized and unified handling of exceptions that occur in the code. An exception is thrown directly in the code block, and the code block does not handle the exception, but deals with the exception together.

Keywords in php exception handling:

Try: monitoring code block

Catch: catching exceptions

Throw: throwing an exception

Finally: it is executed regardless of whether there is an exception or not, and can be omitted.

Exception: exception class

Exception handling syntax structure: try {/ / detect code} catch (Exception $ex) {/ / catch exception} finally {/ / execute regardless of whether there is an exception or not, and finally can be omitted. } sample code: if (isset ($_ POST ['button'])) {try {$age = $_ POST [' age'] If ($age=='') {throw new Exception ('age cannot be empty', 1001) / / throw exception} if (! is_numeric ($age)) {throw new Exception ('age must be numeric' 1002) / / throw exception} if (($age=125) {throw new Exception ('age must be 1-125 years old 1003) / / throw exception} catch (Exception $ex) {/ / catch exception echo' error message'. $ex- > getMessage () Echo 'error code'. $ex- > getCode (); echo 'file address'. $ex- > getFile (); echo 'error line number'. $ex- > getLine ();} finally {echo 'close database connection'; / / execute regardless of whether there is an exception or not, and finally can be omitted. }}

Note: after an exception is thrown, the execution of the try block is terminated and the execution permission is handed over to the catch block.

This is the end of the article on "how to implement exception handling in php". I hope the above content can be of some help to you, so that you can learn more knowledge. if you think the article is good, please share it for more people to see.

Tags: Processing code age article error more good practical useful information keyword content address number data database file article permission Apple Docker Huawei Linux macOS MariaDB Microsoft MySQL NVidia OPPO Reno Shulou Tech Info NVidia OPPO Reno Docker vpn