Extended PHP built-in exception handling class, PHP built-in exception handling _php tutorial

Source: Internet
Author: User
Tags php exception handling try catch

Extended PHP built-in exception handling class, PHP built-in exception handling

In a try code block, you need to throw an exception object with the throw statement to jump to the catch code block and capture and use the object of the exception class in the Catch block. Although the built-in exception handling class exception provided in PHP has a very good feature, in some cases it may be possible to extend this class to get more functionality. So users can use custom exception handling classes to extend PHP's built-in exception handling classes. The following code illustrates which properties and methods are accessible and inheritable in a subclass of the built-in exception-handling class:

12345678910111213141516171819 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 just a description of the structure of the built-in exception handler class exception, which is not a useful code. If you use a custom class as an exception-handling class, you must be a subclass of the extended built-in exception-handling class exception, and subclasses of non-exception classes cannot be used as exception-handling classes. If you redefine the constructor when you extend the built-in exception-handling class Excepiton, it is recommended that you call Parent::construct () at the same time to check that all variables have been assigned values. You can overload __tostring () and customize the style of the output when the object is about to output a string. You can use built-in exceptions to handle all member properties in the exception class directly in a custom subclass, but you cannot rewrite the member methods inherited from the parent class, because most public methods of the class are final.
Creating a custom exception handler is as simple as declaring a traditional class, but the class must be an extension of the built-in exception-handling class exception. When an exception occurs in PHP, you can call the method in the custom exception class to handle it. Creates a custom myexception class that inherits all the properties from the built-in exception handling class exception and adds a custom method to it. The code and application are as follows:

123456789101112131415161718192021222324252627282930 //滴定仪一个异常处理类,但必须是扩展内异常处理类的子类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."
;}//为这个异常自定义一个处理方法public function customFunction(){echo "按自定义的方法处理出现的这个类型的异常
;}} try{$error='允许抛出这个错误'; throw new MyException($error); //创建一个自定义异常的处理对象,通过throw语句抛出echo 'Never executed'; //从这里开始,try代码块内的代码将不会再被执行}catch(MyException $e){ //捕获自定义的异常对象echo '捕获异常:'.$e; //输出捕获的异常消息$e->customFunction(); //通过自定义的异常对象中的方法处理异常} echo '你好呀'; //程序没有崩溃继续向下执行?>

In the custom myexcepition class, use the constructor method in the parent class to check that all variables have been assigned values. It also overloads the __tostring () method in the parent class, outputting its own custom-caught exception-handling class, with little difference in usage, except that in a custom exception-handling class, a specially written processing method for a specific exception can be invoked.

>> This article fixed link: http://php.ncong.com/php_course/wrong/yichangchulilei.html

>> reprint Please specify: Ntshongwana PHP August 06, 2014 Yuncon PHP Learning tutorial Published

Some questions about PHP exception handling

I have discussed this issue with my colleagues a few days ago. I'm going to explain this.

For example, you call the try catch, the array exceeded, the program how to know that the array is exceeded, it must be the array class reported.
and the array class inside, must be throw out, you can catch to, get message, array exceeded, but if the array class inside, directly catch, there is no exception! This way you call the array even if it is exceeded, your own catch is not catch, because no one throws an exception

Other people's answers are too Mandarin to accept my

Several ways to use PHP custom exception handlers

We introduce this PHP custom exception handler as PHP's built-in Exception_uncaught_handler () function. This function can be used to set user-defined exception handlers to handle uncaught exceptions for Trycatch blocks.
The following 4 pieces of code for my simple application in the Waylife project (non-production environment), not robust or landscaping, but the SNS project has been premature.
1, the level of the exception class relationship:
2. Configure the processor that does not catch the exception:
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 Sky
, manually throwing a dbexception exception but not using Trycatch for capture processing, 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 are visiting does not exist ');

http://www.bkjia.com/PHPjc/870653.html www.bkjia.com true http://www.bkjia.com/PHPjc/870653.html techarticle extended PHP built-in exception handling class, PHP built-in exception handling in the try code block, you need to use the throw statement to throw an exception object to jump to the catch code block to execute, and in C ...

  • Related Article

    Contact Us

    The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

    If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

    A Free Trial That Lets You Build Big!

    Start building with 50+ products and up to 12 months usage for Elastic Compute Service

    • Sales Support

      1 on 1 presale consultation

    • After-Sales Support

      24/7 Technical Support 6 Free Tickets per Quarter Faster Response

    • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.