Table of Contents
Detailed explanation of exception examples captured by try catch in php, trycatch
Home Backend Development PHP Tutorial 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_PHP tutorial

Jul 13, 2016 am 10:13 AM
catch php try

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)

Copy code The code is as follows:
try{
}
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():

Copy code The code is as follows:
try {
$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

Copy code The code is as follows:
// Wrong demo
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:

Copy code The code is as follows:
Class MyException extends Exception{
//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.

www.bkjia.comtruehttp: //www.bkjia.com/PHPjc/915425.htmlTechArticleDetailed explanation of try catch exception examples in php, trycatch This article describes the try catch exception example in php. Share it with everyone for your reference. The specific method is analyzed as follows: try catch in php can...
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

Video Face Swap

Video Face Swap

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

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)

PHP 8.4 Installation and Upgrade guide for Ubuntu and Debian PHP 8.4 Installation and Upgrade guide for Ubuntu and Debian Dec 24, 2024 pm 04:42 PM

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

How To Set Up Visual Studio Code (VS Code) for PHP Development How To Set Up Visual Studio Code (VS Code) for PHP Development Dec 20, 2024 am 11:31 AM

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

7 PHP Functions I Regret I Didn't Know Before 7 PHP Functions I Regret I Didn't Know Before Nov 13, 2024 am 09:42 AM

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

How do you parse and process HTML/XML in PHP? How do you parse and process HTML/XML in PHP? Feb 07, 2025 am 11:57 AM

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

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,

PHP Program to Count Vowels in a String PHP Program to Count Vowels in a String Feb 07, 2025 pm 12:12 PM

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

Explain late static binding in PHP (static::). Explain late static binding in PHP (static::). Apr 03, 2025 am 12:04 AM

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 PHP magic methods (__construct, __destruct, __call, __get, __set, etc.) and provide use cases? What are PHP magic methods (__construct, __destruct, __call, __get, __set, etc.) and provide use cases? Apr 03, 2025 am 12:03 AM

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.

See all articles