


PHP object-oriented programming (oop) study notes (4) - Exception handling class Exception_PHP tutorial
Usage exception
PHP5 adds exception handling modules similar to other languages. Exceptions generated in PHP code can be thrown by the throw statement and caught by the catch statement. Code that requires exception handling must be placed in a try code block to catch possible exceptions. Each try corresponds to at least one catch block. Use multiple catches to catch exceptions generated by different classes. When the try block no longer throws an exception or no catch is found that matches the thrown exception, the PHP code continues execution after jumping to the last catch. Of course, PHP allows exceptions to be thrown again within catch blocks.
Predefined exception Exception
The Exception class is the base class for all exceptions. We can derive custom exceptions by deriving the Exception class. The following list lists basic information about Exception.
Exception {
/* Attributes*/
protected string $message; //Exception message content
protected int $code; //Exception code
protected string $file; //Exception file name
protected int $line; //Exception thrown in the file Line number
/* Method*/
public __construct ([ string $message = "" [, int $code = 0 [, Exception $previous = NULL ]]] ) //Exception constructor
final public string getMessage (void) //Get the exception message content
final public Exception getPrevious (void) //Return the previous exception in the exception chain
final public int getCode (void) //Get the exception code
final public string getFile ( void ) // Get the name of the program file where the exception occurred
final public int getLine ( void ) // Get the line number of the code in the file where the exception occurred
final public array getTrace ( void ) //Get exception tracking information
final public string getTraceAsString (void) //Get exception tracking information of string type
public string __toString (void) //Convert the exception object to a string
final private void __clone (void) //Exceptional clone
}
After understanding Exception, let’s try to extend the exception class to implement a custom exception.
function connectToDatabase()
{
if(!$link = mysql_connect ("myhost","myuser","mypassw","mybd"))
{
throw new Exception("could not connect to the database.");
}
}
try
{
connectToDatabase();
}
catch(Exception $e)
{echo $e->getMessage();
}
Here we throw an Exception type exception, catch this exception in catch, and finally print out "could not connect to the database.". Maybe you want to also display information about why the database connection failed. Next, we implement our custom information by extending the exception class.
class MyException extends Exception
{
protected $ErrorInfo;
//Process some logic in the constructor, and then pass some information to the base class
public function __construct($message =null,$code=0)
{
$this->ErrorInfo = 'Error message of custom error class';
parent::__construct($message,$code);
} */
public function log($file)
{
file_put_contents($fiel,$this->__toString(),FILE_APPEND);
}
}
function connectToDatabase( )
{
throw new MyException("ErrorMessage");
}
try
{
connectToDatabase();
}
catch(MyException $e)
{
echo $e->getMessage() . "n";
echo $e->GetErrorInfo();
}
set_exception_handler sets a user-defined exception handling function
The name of the function called when an uncaught exception occurs as a parameter to set_exception_handler. This function must be defined before calling set_exception_handler(). This function accepts one parameter, which is a thrown exception object. This can be used to improve the exception logging handling mentioned above.
Copy code
function ExceptionLogger($exception)
{$file='ExceptionLog .log';
Copy code
The code is as follows:
try
{#code...
else
{
throw $e;
}
}
Summary
The exception function is very powerful, but it does not mean that we can abuse the exception mechanism wantonly in the project, especially the mechanism of extensive use of exception logs, which will greatly increase the system overhead and reduce the performance of the application. We can use error codes to easily manage error messages. When an error message is thrown multiple times, using error codes is a scientific choice. We can even use error codes to display error messages in multiple languages.
http://www.bkjia.com/PHPjc/788632.html
TechArticle

PHP is used to build dynamic websites, and its core functions include: 1. Generate dynamic content and generate web pages in real time by connecting with the database; 2. Process user interaction and form submissions, verify inputs and respond to operations; 3. Manage sessions and user authentication to provide a personalized experience; 4. Optimize performance and follow best practices to improve website efficiency and security.

PHP uses MySQLi and PDO extensions to interact in database operations and server-side logic processing, and processes server-side logic through functions such as session management. 1) Use MySQLi or PDO to connect to the database and execute SQL queries. 2) Handle HTTP requests and user status through session management and other functions. 3) Use transactions to ensure the atomicity of database operations. 4) Prevent SQL injection, use exception handling and closing connections for debugging. 5) Optimize performance through indexing and cache, write highly readable code and perform error handling.

Using preprocessing statements and PDO in PHP can effectively prevent SQL injection attacks. 1) Use PDO to connect to the database and set the error mode. 2) Create preprocessing statements through the prepare method and pass data using placeholders and execute methods. 3) Process query results and ensure the security and performance of the code.

PHP and Python have their own advantages and disadvantages, and the choice depends on project needs and personal preferences. 1.PHP is suitable for rapid development and maintenance of large-scale web applications. 2. Python dominates the field of data science and machine learning.

PHP is widely used in e-commerce, content management systems and API development. 1) E-commerce: used for shopping cart function and payment processing. 2) Content management system: used for dynamic content generation and user management. 3) API development: used for RESTful API development and API security. Through performance optimization and best practices, the efficiency and maintainability of PHP applications are improved.

PHP makes it easy to create interactive web content. 1) Dynamically generate content by embedding HTML and display it in real time based on user input or database data. 2) Process form submission and generate dynamic output to ensure that htmlspecialchars is used to prevent XSS. 3) Use MySQL to create a user registration system, and use password_hash and preprocessing statements to enhance security. Mastering these techniques will improve the efficiency of web development.

PHP and Python each have their own advantages, and choose according to project requirements. 1.PHP is suitable for web development, especially for rapid development and maintenance of websites. 2. Python is suitable for data science, machine learning and artificial intelligence, with concise syntax and suitable for beginners.

PHP is still dynamic and still occupies an important position in the field of modern programming. 1) PHP's simplicity and powerful community support make it widely used in web development; 2) Its flexibility and stability make it outstanding in handling web forms, database operations and file processing; 3) PHP is constantly evolving and optimizing, suitable for beginners and experienced developers.


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

AI Hentai Generator
Generate AI Hentai for free.

Hot Article

Hot Tools

PhpStorm Mac version
The latest (2018.2.1) professional PHP integrated development tool

SublimeText3 English version
Recommended: Win version, supports code prompts!

WebStorm Mac version
Useful JavaScript development tools

SAP NetWeaver Server Adapter for Eclipse
Integrate Eclipse with SAP NetWeaver application server.

Zend Studio 13.0.1
Powerful PHP integrated development environment