Home php教程 php手册 PHP中Exception异常处理类的使用详解

PHP中Exception异常处理类的使用详解

Jun 13, 2016 am 10:01 AM
exception php use exist deal with abnormal article use of Simple kind Detailed explanation

本文章介绍了在php中常用的简单的异常处理类,我们主要是讲述到了Exception处理 ,有需要了解的同学可参考一下。

 代码如下 复制代码
    try {
        $a=10/0;
    }catch (Exception $e){
        echo "抛出异常";
    }
?>

以上代码,并不会输出“抛出异常”,而是输出了错误信息:Warning: Division by zero in......

说明:try块中并没有抛出异常,而是按照系统默认的错误处理机制进行处理

所以能不能捕获到异常,取决于有没有真正的抛出异常

 

 代码如下 复制代码

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();                       // 可输出的字符串
}
?>

简单的使用如下:(通过异常,抛出错误信息)

 代码如下 复制代码

try {
    $error = 'my error!';
    throw new Exception($error)
} catch (Exception $e) {
    echo $e->getMessage();
}

我们可以扩展此类,方便我们的使用

 

 代码如下 复制代码

class MyException extends Exception
{
    // 重定义构造器使 message 变为必须被指定的属性
    public function __construct($message, $code = 0) {
        // 自定义的代码

        // 确保所有变量都被正确赋值
        parent::__construct($message, $code);
    }

    // 自定义字符串输出的样式
    public function __toString() {
        return __CLASS__ . ": [{$this->code}]: {$this->message}n";
    }

    public function customFunction() {
        echo "A Custom function for this type of exceptionn";
    }
}
  

异常处理的基本思想是代码在try代码被调用执行。如果try码块出现错误,我们可以执行一个抛出异常的处理。某些编程语言,如java,,在特定情况下将自动抛出异常。在php中,异常必须手动抛出。可以使用如下方式抛出一个异常:

 代码如下 复制代码

  Throw new Exception(‘message’,code);

  Throw 关键字将触发异常处理机制,它是一个语言结构,而不是一个函数,但是必须给它传递一个值。它要求一个接受对象。在最简单的情况下,可以实例化一个内置的Exception类。

  最后,在try代码之后,必须至少给出一个catch代码块。可以将多个catch代码块与一个try代码块进行关联。如果每个catch代码块可以捕获一个不同类型的异常,可以使用多个catch代码块是有意义的。例如,如果想捕获Exception类的异常,代码如下

 

 代码如下 复制代码

Catch(Exception $e)

{

   //handing exception

}

Catch代码捕获的对象就是导致异常并传递给throw语句的对象(被throw 语句抛出)。使用Exception 类的实例,是不错的选择。

Exception类提供了如下的内置方法:

  Getcode()      —返回传递给构造函数的代码。

  GetMessage()    —返回传递给构造函数的消息。

  getFile()     —返回产生异常代码的文件的路径

  getLine()    —返回产生异常的代码所在的行。
注意:

当捕获到一个异常后,try()块里面的后续代码将不会继续执行,而是会尝试查找匹配的“catch”代码块
 当抛出一个异常后,如果不进行catch处理,则会报“Uncaught exception 'Exception'”错误

 代码如下 复制代码
    function test($val){
        if ($val>100){
            throw new Exception("提示信息:您输入的值过大");
        }
    }
    test(111);
?>

  3.当一个异常抛出后,catch语句块可以进行处理也可以不处理

以下是我用户注册功能的部分代码

try{
     //check forms filled in
     if(!filled_out($_POST)){
         throw new Exception('你还没有填写表单,请回去填写');
     }
     //check email address not valid
     if(!check_email($email)){
        throw new Exception('邮件的格式不正确');
     }
     //检查密度的长度是否大于6
     if(strlen($passwd          throw new Exception('密度的长度应该大于6');
     }
     //检查两次密码是否相等
     if($passwd!=$passwd1){
         throw new Exception('两次密码不一样,请重新输入');
     }
     //检查用户名的长度是否正确
     if(strlen($username)>16){
         throw new Exception('用户名的长度不符,请重新输入');
     }
  
 } catch(Exception $e){
     echo $e->getMessage(); //输出异常信息。
 }

 

php对异常的处理与java一样,用到的是try{}catch(){}

定义顶级异常处理器用到的函数是
set_exception_handler("My_exception");
这里的My_expection是开发者自定义的异常处理函数,既顶级异常处理器,只有当程序中没有函数来处理异常才有顶级异常处理器来处理异常,如果没有定义顶级异常处理器,则由系统默认的异常处理器来处理异常
举例说明:

 代码如下 复制代码
    set_exception_handler("My_expection");
    function My_expection(){
        echo "这里是顶级异常处理器";
    }
    try{
        nohello("hello");
    }catch(Exception $e){
        throw $e;
    }
  function nohello($nohello){
          if($nohello == "hello"){
              throw new Exception("不能输入hello");
          }else{
            echo "输入成功";
        }
    }
?>

 

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 Article

Roblox: Bubble Gum Simulator Infinity - How To Get And Use Royal Keys
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Nordhold: Fusion System, Explained
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Mandragora: Whispers Of The Witch Tree - How To Unlock The Grappling Hook
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌

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)

Hot Topics

Java Tutorial
1670
14
PHP Tutorial
1274
29
C# Tutorial
1256
24
PHP: A Key Language for Web Development PHP: A Key Language for Web Development Apr 13, 2025 am 12:08 AM

PHP is a scripting language widely used on the server side, especially suitable for web development. 1.PHP can embed HTML, process HTTP requests and responses, and supports a variety of databases. 2.PHP is used to generate dynamic web content, process form data, access databases, etc., with strong community support and open source resources. 3. PHP is an interpreted language, and the execution process includes lexical analysis, grammatical analysis, compilation and execution. 4.PHP can be combined with MySQL for advanced applications such as user registration systems. 5. When debugging PHP, you can use functions such as error_reporting() and var_dump(). 6. Optimize PHP code to use caching mechanisms, optimize database queries and use built-in functions. 7

PHP vs. Python: Understanding the Differences PHP vs. Python: Understanding the Differences Apr 11, 2025 am 12:15 AM

PHP and Python each have their own advantages, and the choice should be based on project requirements. 1.PHP is suitable for web development, with simple syntax and high execution efficiency. 2. Python is suitable for data science and machine learning, with concise syntax and rich libraries.

PHP and Python: Comparing Two Popular Programming Languages PHP and Python: Comparing Two Popular Programming Languages Apr 14, 2025 am 12:13 AM

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 in Action: Real-World Examples and Applications PHP in Action: Real-World Examples and Applications Apr 14, 2025 am 12:19 AM

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.

The Enduring Relevance of PHP: Is It Still Alive? The Enduring Relevance of PHP: Is It Still Alive? Apr 14, 2025 am 12:12 AM

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.

PHP and Python: Different Paradigms Explained PHP and Python: Different Paradigms Explained Apr 18, 2025 am 12:26 AM

PHP is mainly procedural programming, but also supports object-oriented programming (OOP); Python supports a variety of paradigms, including OOP, functional and procedural programming. PHP is suitable for web development, and Python is suitable for a variety of applications such as data analysis and machine learning.

PHP vs. Other Languages: A Comparison PHP vs. Other Languages: A Comparison Apr 13, 2025 am 12:19 AM

PHP is suitable for web development, especially in rapid development and processing dynamic content, but is not good at data science and enterprise-level applications. Compared with Python, PHP has more advantages in web development, but is not as good as Python in the field of data science; compared with Java, PHP performs worse in enterprise-level applications, but is more flexible in web development; compared with JavaScript, PHP is more concise in back-end development, but is not as good as JavaScript in front-end development.

PHP and Python: Code Examples and Comparison PHP and Python: Code Examples and Comparison Apr 15, 2025 am 12:07 AM

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.

See all articles