Home  >  Article  >  Backend Development  >  Extend PHP's built-in exception handling class, PHP's built-in exception handling_PHP tutorial

Extend PHP's built-in exception handling class, PHP's built-in exception handling_PHP tutorial

WBOY
WBOYOriginal
2016-07-13 10:19:55891browse

Extend PHP's built-in exception handling class, PHP's built-in exception handling

In the try code block, you need to use the throw statement to throw an exception object before jumping to the catch code block, and capture and use the object of this exception class in the catch code block. Although the built-in exception handling class Exception provided in PHP already has very good features, in some cases, this class may need to be extended to get more functions. Therefore, users can use custom exception handling classes to extend PHP's built-in exception handling classes. The following code illustrates which properties and methods in the built-in exception handling class are accessible and inheritable in subclasses:

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 <?php class Exception{ protected $message = 'Unknown exception'; //异常信息 protected $code = 0; //用户自定义异常代码 protected $file; //发生异常的文件名 protected $line; //发生异常的代码行号 function __construct($message =null,$code=0){} final function getMessage(){} //返回异常信息 final function getCode(){} //返回异常代码 final function getFile(){} //返回发生异常的文件名 final function getLine(){} //返回发生异常的代码行号 final function getTrace(){} //backtrace()数组 final function getTraceAsString(){} //已格式化成字符串的getTrace()信息 //可重载的方法,可输出字符串 function __toString(){} } ?>

The above code is only to illustrate the structure of the built-in exception handling function class Exception. It is not a usable code with practical significance. If you use a custom class as an exception handling class, it must be a subclass that extends the built-in exception handling class Exception. Subclasses of non-Exception classes cannot be used as exception handling classes. If you redefine the constructor when extending the built-in exception handling class Excepiton, it is recommended to call parent::construct() at the same time to check whether all variables have been assigned values. When the object wants to output a string, you can overload __toString() and customize the output style. You can directly use the built-in exception handling in a custom subclass to handle all member attributes in the Exception class, but you cannot rewrite the member methods inherited from the parent class because most of the public methods of this class are final.
Creating a custom exception handler is very simple and is declared in the same way as a traditional class, but the class must be an extension of the built-in exception handling class Exception. When an exception occurs in PHP, methods in the custom exception class can be called to handle it. Create a custom MyException class, inherit all properties from the built-in exception handling class Exception, and add custom methods to it. The code and application are as follows:

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 <?php //滴定仪一个异常处理类,但必须是扩展内异常处理类的子类 class MyException extends Exception{ //重定义构造器使第一个参数message变为必须被指定属性 public function __construct($message,$code=0){ //在这里定义一些自己的代码 //建议同时调用parent::construct()来检查所有的变量是否已被赋值 parent::__construct($message,$code); } //重写父类方法,自定义字符串输出的样式 public function __toString(){ return __CLASS__.":[".$this->code."]:".$this->message."<br>"; } //为这个异常自定义一个处理方法 public function customFunction(){ echo "按自定义的方法处理出现的这个类型的异常<br>"; } }   try{ $error='允许抛出这个错误'; throw new MyException($error); //创建一个自定义异常的处理对象,通过throw语句抛出 echo 'Never executed'; //从这里开始,try代码块内的代码将不会再被执行 }catch(MyException $e){ //捕获自定义的异常对象 echo '捕获异常:'.$e; //输出捕获的异常消息 $e->customFunction(); //通过自定义的异常对象中的方法处理异常 }   echo '你好呀'; //程序没有崩溃继续向下执行 ?>

In the customized MyExcepition class, use the constructor method in the parent class to check whether all variables have been assigned values. Moreover, the __toString() method in the parent class is overloaded to output the exception handling class that is customized and captured. There is not much difference in use, except that in the custom exception handling class, you can call the exception handling class specially written for specific exceptions. Processing methods.

>> Fixed link to this article: http://php.ncong.com/php_course/wrong/yichangchulilei.html

>> Please indicate when reprinting: Encongphp published in Encong PHP Learning Tutorial on August 6, 2014

Some issues with PHP exception handling

I also discussed this issue with my colleagues a few days ago. Let me explain it this way

For example, if you call try catch and the array exceeds the standard, how does the program know that the array exceeds the standard? It must be reported by the array class.
In the array class, you must throw it out so that you can catch and get the message. The array exceeds the standard. But if you catch it directly in the array class, there will be no exception! In this way, even if the array you call exceeds the standard, your own catch will not be able to catch it, because no one throws an exception

Other people’s answers are too official, please accept mine

Several ways to use PHP custom exception handler

The PHP custom exception handler we introduced is PHP’s built-in exception_uncaught_handler() function. This function can be used to set a user-defined exception handling function to handle exceptions uncaught by the trycatch block.
The following 4 pieces of code are my simple applications in the waylife project (non-production environment). They are not robust and not beautiful, but the SNS project has long since died.
1. Hierarchical relationship of exception classes:
classNotFoundExceptionextendsException{}
classInputExceptionextendsException{}
classDBExceptionextendsException{}
2. Configure the handler for uncaught exceptions:
functionexception_uncaught_handler(Exception$e ){
header('Content-type:text/html;charset=utf-8');if($einstanceofNotFoundException)exit($e-
getMessage());
elseif($einstanceofDBException) exit($e-
getMessage());elseexit($e-
getMessage());}set_exception_handler('exception_uncaught_handler');
3. In the database connection code source code Sky
, manually If a DBException is thrown but is not captured using trycatch, the exception will be handled by the PHP custom exception handler exception_uncaught_handler() function: $this-resConn=mysql_connect
($CONFIGS['db_host'],$CONFIGS[' db_user'],$CONFIGS['db_pwd']);if(false==is_resource($this-resConn))thrownewDBException('Database connection failed.'.mysql_error($this-resConn)); 4. Business logic at a glance:
if(0!=strcmp($curAlbum-
interest_id,$it))
thrownewNotFoundException('Sorry, the album you visited does not exist');

www.bkjia.comtruehttp: //www.bkjia.com/PHPjc/870653.htmlTechArticleExtend PHP’s built-in exception handling class. PHP’s built-in exception handling is in the try code block and needs to be thrown using the throw statement. An exception object can jump to the catch code block for execution, and execute it in c...
Statement:
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