


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

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

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



In Java, when multiple threads operate a collection object at the same time, a ConcurrentModificationException exception may occur. This exception usually occurs when traversing the collection when modifying or deleting elements. This will cause the state of the collection to be inconsistent, thus throwing abnormal. This article will delve into the causes and solutions to this exception. 1. Causes of Exception Normally, ConcurrentModificationException exception

In PHP development, you may encounter errors such as "PHPFatalerror:Uncaughtexception'PDOException'". This is an exception caused by an error when PHP operates the database. If this error is not handled in time, it will cause program interruption or unexpected errors. So how to solve this problem? Here are some common solutions. 1. Check the database parameters. First, we need to check the parameters passed when connecting to the database.

How to deal with UnsupportedEncodingException in Java? In Java programming, you may encounter UnsupportedEncodingException. This exception is usually caused by incorrect encoding conversion or an unsupported encoding. In this article, we will introduce the causes of UnsupportedEncodingException exception and how to deal with it. What is UnsupportedE

What are the common causes of ConcurrentModificationException in Java? When traversing a collection using an iterator in the Java collection framework, a ConcurrentModificationException exception is sometimes thrown, which is one of the common Java exceptions. So, what is the reason for this exception? First, we need to understand that the iterators provided by the Java collection framework are stateful. That is, when traversing

In Java development, we often use arrays to store a series of data because of the convenience and performance advantages of arrays. However, in the process of using arrays, some exceptions will occur, and one of the common exceptions is ArrayStoreException. This exception is thrown when we store incompatible data types in the array. This article will introduce what an ArrayStoreException is, why it occurs, and how to solve it. 1. Arr

In Java programming, array is an important data structure. Arrays can store multiple values in a single variable, and more importantly each value can be accessed using an index. But while working with arrays, some exceptions may occur, one of them is ArrayStoreException. This article will discuss common causes of ArrayStoreException exceptions. 1. Type mismatch The element type must be specified when the array is created. When we try to store incompatible data types into an array, it throws

UnsupportedEncodingException may occur in Java, mainly because the encoding is not supported. When processing text data, it is often necessary to perform encoding conversion, that is, to convert the content of one encoding format into the content of another encoding format. If the encoding type used for encoding conversion is not supported, an UnsupportedEncodingException will be thrown. This article will introduce the solution to this exception. one,

The Exception class and the Error class are both subclasses of the java.lang.Throwable class. We can handle runtime exceptions, but not errors. Exceptions are objects that represent logical errors that occur at runtime, causing the JVM to enter an "ambiguous" state. Objects automatically created by the JVM to represent these runtime errors are called exceptions. Error is a subclass of the Throwable class that indicates serious problems that reasonable applications should not try to catch. Most of these errors are anomalies. If an exception occurs, we can use try and catch blocks to handle it. If an error occurs that we cannot handle, the program will terminate. There are two types of exceptions, one is CheckedExce
