


Detailed explanation of exception examples captured by try catch in php, trycatch_PHP tutorial
Detailed explanation of exception examples captured by try catch in php, trycatch
The example in this article tells about try catch catching exceptions in php. Share it with everyone for your reference. The specific method analysis is as follows:
try catch in php can help us catch exceptions in program code, so that we can handle some unnecessary errors well. Interested friends can take a look.
Overview of try{}catch{} statement in PHP
PHP5 adds an exception handling module similar to other languages. Exceptions generated in PHP code can be thrown by the throw statement and caught by the catch statement. (Note: You must throw it first to get it)
Code that requires exception handling must be placed in a try code block to catch possible exceptions.
Each try must have at least one corresponding catch.
Use multiple catches to catch exceptions generated by different classes.
When the try code block no longer throws an exception or no catch can be found to match the thrown exception, the PHP code will continue execution after jumping to the last catch.
Of course, PHP allows exceptions to be thrown again within catch blocks.
When an exception is thrown, the subsequent code (Translator's Note: refers to the code block when the exception is thrown) will not continue to execute, and PHP will try to find the first matching catch.
If an exception is not caught and there is no need to use set_exception_handler() for corresponding processing, then PHP will generate a serious error and output an Uncaught Exception... (uncaught exception) prompt message.
First, let’s take a look at the basic properties and methods of PHP’s built-in exception class. (excluding specific implementation)
}
catch(){
throw new Exception();
}
catch(){
//Here you can catch the Exception thrown by the previous block
}
In order to further handle the exception, we need to use try{}catch{} in PHP----including Try statement and at least one catch statement. Any code that calls a method that may throw an exception should use a try statement. The Catch statement is used to handle exceptions that may be thrown. The following shows how we handle exceptions thrown by getCommandObject():
$mgr = new CommandManager();
$cmd = $mgr->getCommandObject("realcommand");
$cmd->execute();
} catch (Exception $e) {
print $e->getMessage();
exit();
}
?>
As you can see, by using the throw keyword in conjunction with try{}catch{} in PHP, we can avoid error markers "polluting" the values returned by class methods. Because "exception" itself is a PHP built-in type that is different from any other object, there will be no confusion.
If an exception is thrown, the script in the try statement will stop executing, and then immediately switch to executing the script in the catch statement.
Examples are as follows:
Include file error throws exception
try {
require ('test_try_catch.php');
} catch (Exception $e) {
echo $e->getMessage();
}
// Throw exception correctly
try {
if (file_exists('test_try_catch.php')) {
require ('test_try_catch.php');
} else {
throw new Exception('file is not exists');
}
} catch (Exception $e) {
echo $e->getMessage();
}
If an exception is thrown but not caught, a fatal error will occur.
Multiple catches to catch multiple exceptions
PHP will query for a matching catch block. If there are multiple catch blocks, the object passed to each catch block must be of a different type so that PHP can find which catch block it needs to enter. When the try code block no longer throws an exception or no catch can match the thrown exception, the PHP code will continue executing after jumping to the last catch. An example of catching multiple exceptions is as follows:
//Redefine the constructor so that the first parameter message becomes an attribute that must be specified
public function __construct($message, $code=0){
//You can define some of your own code here
//It is recommended to call parent::construct() at the same time to check whether all variables have been assigned
parent ::__construct($message, $code);
}
//Rewrite the inherited method from the parent class and customize the string output style
public function __toString(){
return __CLASS__.":[".$this->code."]:".$this->message."
";
}
//Customize a handling method for this exception
public function customFunction(){
echo "Handle exceptions of this type in a custom way";
}
}
//Create an exception class MyException
for testing custom extensions Class TestException{
Public $var; //Member attributes used to determine whether the object is successfully created
function __construct($value=0){ //The exception thrown is determined by the value passed in the constructor
switch($value){ Case 1: // Bleast the parameter 1, then throw a custom abnormal object
throw new MyException("The value "1" passed in is an invalid parameter",5);break;
Case 2: // Pass parameter 2, then throw the PHP built -in abnormal object
throw new MyException("The value passed in "2" is not allowed as a parameter", 6); break;
Default: // The parameter is legal, but the abnormality is not thrown
}
}
}
//Example 1, when there is no exception, the program executes normally, all codes in try are executed and no catch block is executed
Try{
$ Testobj = new testxception (); // Use the default parameter to create an abnormal wiping object
echo "********
"; //If no exception is thrown, this statement will be executed normally
} Catch (MyException $ E) {// Capture the user's custom abnormal block
echo "Capture custom exception: $e
"; //Output the exception message in a customized way
}catch(Exception $e){ // Capture the object of PHP’s built-in exception handling class
echo "Capture the default exception:".$e->getMessage()."
"; //Output exception message
}
var_dump($testObj); //Determine whether the object is created successfully. If there are no exceptions, the creation is successful
//Example 2, throw a custom exception, catch this exception through a custom exception handling class and handle it
Try{
$testObj1 =new TestException(1); //When passing 1, a custom exception is thrown
echo "********
"; //This statement will not be executed
}catch(MyException $e){ // The code in this catch block will be executed
echo "Catch custom exception: $e
"; $e->customFunction(); }catch(Exception $e){ // This catch block will not be executed
echo "Catch the default exception:".$e->getMessage()."
";
}
var_dump($testObj1); //An exception occurred and this object was not created successfully
//Example 2, throw a built-in exception, catch this exception through a custom exception handling class and handle it
Try{
$ TestObj2 = New Testexception (2); // Pass at 2, throw the built -in abnormalities
echo "********
"; //This statement will not be executed
}catch(MyException $e){ // The code in this catch block will be executed
echo "Catch custom exception: $e
"; $e->customFunction(); }catch(Exception $e){ // This catch block will not be executed
echo "Catch the default exception:".$e->getMessage()."
";
}
var_dump($testObj2); //An exception occurred and this object was not created successfully
?>
In the above code, you can use two exception handling classes: one is the custom exception handling class MyException; the other is the built-in exception handling class Exception in PHP. Create objects of the test class TestException in the try block respectively, and according to the different numeric parameters provided in the construction method, throw custom exception class objects, built-in exception class objects, and do not throw any exceptions, jump to the corresponding Executed in the catch block. If no exception occurs, it will not enter any catch block for execution, and the object of the test class TestException is successfully created
I hope this article will be helpful to everyone’s PHP programming design.

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

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

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics



PHP 8.4 brings several new features, security improvements, and performance improvements with healthy amounts of feature deprecations and removals. This guide explains how to install PHP 8.4 or upgrade to PHP 8.4 on Ubuntu, Debian, or their derivati

Visual Studio Code, also known as VS Code, is a free source code editor — or integrated development environment (IDE) — available for all major operating systems. With a large collection of extensions for many programming languages, VS Code can be c

If you are an experienced PHP developer, you might have the feeling that you’ve been there and done that already.You have developed a significant number of applications, debugged millions of lines of code, and tweaked a bunch of scripts to achieve op

This tutorial demonstrates how to efficiently process XML documents using PHP. XML (eXtensible Markup Language) is a versatile text-based markup language designed for both human readability and machine parsing. It's commonly used for data storage an

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,

A string is a sequence of characters, including letters, numbers, and symbols. This tutorial will learn how to calculate the number of vowels in a given string in PHP using different methods. The vowels in English are a, e, i, o, u, and they can be uppercase or lowercase. What is a vowel? Vowels are alphabetic characters that represent a specific pronunciation. There are five vowels in English, including uppercase and lowercase: a, e, i, o, u Example 1 Input: String = "Tutorialspoint" Output: 6 explain The vowels in the string "Tutorialspoint" are u, o, i, a, o, i. There are 6 yuan in total

Static binding (static::) implements late static binding (LSB) in PHP, allowing calling classes to be referenced in static contexts rather than defining classes. 1) The parsing process is performed at runtime, 2) Look up the call class in the inheritance relationship, 3) It may bring performance overhead.

What are the magic methods of PHP? PHP's magic methods include: 1.\_\_construct, used to initialize objects; 2.\_\_destruct, used to clean up resources; 3.\_\_call, handle non-existent method calls; 4.\_\_get, implement dynamic attribute access; 5.\_\_set, implement dynamic attribute settings. These methods are automatically called in certain situations, improving code flexibility and efficiency.
