Table of Contents
php中try catch捕获异常实例详解,trycatch
Home php教程 php手册 php中try catch捕获异常实例详解,trycatch

php中try catch捕获异常实例详解,trycatch

Jun 13, 2016 am 09:20 AM
catch php try

php中try catch捕获异常实例详解,trycatch

本文实例讲述了php中try catch捕获异常。分享给大家供大家参考。具体方法分析如下:

php中try catch可以帮助我们捕获程序代码的异常了,这样我们可以很好的处理一些不必要的错误了,感兴趣的朋友可以一起来看看。

PHP中try{}catch{}语句概述

PHP5添加了类似于其它语言的异常处理模块。在 PHP 代码中所产生的异常可被 throw语句抛出并被 catch 语句捕获。(注:一定要先抛才能获取)

需要进行异常处理的代码都必须放入 try 代码块内,以便捕获可能存在的异常。

每一个 try 至少要有一个与之对应的 catch。

使用多个 catch可以捕获不同的类所产生的异常。

当 try 代码块不再抛出异常或者找不到 catch 能匹配所抛出的异常时,PHP 代码就会在跳转到最后一个 catch 的后面继续执行。

当然,PHP允许在 catch 代码块内再次抛出(throw)异常。

当一个异常被抛出时,其后(译者注:指抛出异常时所在的代码块)的代码将不会继续执行,而 PHP 就会尝试查找第一个能与之匹配的 catch。

如果一个异常没有被捕获,而且又没用使用 set_exception_handler() 作相应的处理的话,那么 PHP 将会产生一个严重的错误,并且输出 Uncaught Exception ... (未捕获异常)的提示信息。

先来看一下PHP内置异常类的基本属性和方法。(不包括具体实现)

复制代码 代码如下:

try{
}
catch(){
throw new Exception();
}
catch(){
//这里可以捕获到前面一个块抛出的Exception
}

为了进一步处理异常,我们需要使用PHP中try{}catch{}----包括Try语句和至少一个的catch语句。任何调用 可能抛出异常的方法的代码都应该使用try语句。Catch语句用来处理可能抛出的异常。以下显示了我们处理getCommandObject()抛出的异常的方法:

复制代码 代码如下:

try {
$mgr = new CommandManager();
$cmd = $mgr->getCommandObject("realcommand");
$cmd->execute();
} catch (Exception $e) {
print $e->getMessage();
exit();
}
?>


可以看到,通过结合使用throw关键字和PHP中try{}catch{},我们可以避免错误标记“污染”类方法返回的值。因为“异常”本身就是一种与其它任何对象不同的PHP内建的类型,不会产生混淆。

如果抛出了一个异常,try语句中的脚本将会停止执行,然后马上转向执行catch语句中的脚本。

例子如下:

包含文件错误抛出异常

复制代码 代码如下:

// 错误的演示
try {
require ('test_try_catch.php');
} catch (Exception $e) {
echo $e->getMessage();
}

// 正确的抛出异常
try {
if (file_exists('test_try_catch.php')) {
require ('test_try_catch.php');
} else {
throw new Exception('file is not exists');
}
} catch (Exception $e) {
echo $e->getMessage();
}


如果异常抛出了却没有被捕捉到,就会产生一个fatal error。

多个catch捕获多个异常

PHP将查询一个匹配的catch代码块。如果有多个catch代码块,传递给每一个catch代码块的对象必须具有不同类型,这样PHP可以找到需要进入哪一个catch代码块。当try代码块不再抛出异常或者找不到catch能匹配所抛出的异常时,PHP代码就会在跳转最后一个catch的后面继续执行。多个异常的捕获的示例如下:

复制代码 代码如下:

    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 "按自定义的方法处理出现的这个类型的异常";
           }
    }
 
    //创建一个用于测试自定义扩展的异常类MyException
    class TestException{
        public $var;           //用来判断对象是否创建成功的成员属性
        function __construct($value=0){              //通过构造方法的传值决定抛出的异常
            switch($value){                          //对传入的值进行选择性的判断
                case 1:                              //掺入参数1,则抛出自定义的异常对象
                    throw new MyException("传入的值“1”是一个无效的参数",5);break;
                case 2:                              //传入参数2,则抛出PHP内置的异常对象
                    throw new MyException("传入的值“2”不允许作为一个参数",6);break;
                default:                             //传入参数合法,则不抛出异常
                    $this->var=$value;break;          //为对象中的成员属性赋值
            }
        }
    }
 
    //示例1,在没有异常时,程序正常执行,try中的代码全部执行并不会执行任何catch区块
    try{
        $testObj =new TestException();           //使用默认参数创建异常的擦拭类对象
        echo "********
";                     //没有抛出异常这条语句就会正常执行
    }catch(MyException $e){                      //捕获用户自定义的异常区块
        echo "捕获自定义的异常:$e
";          //按自定义的方式输出异常消息
        $e->customFunction();                    //可以调用自定义的异常处理方法
    }catch(Exception $e){                        //捕获PHP内置的异常处理类的对象
        echo "捕获默认的异常:".$e->getMessage()."
";       //输出异常消息
    }
    var_dump($testObj);        //判断对象是否创建成功,如果没有任何异常,则创建成功
 
    //示例2,抛出自定义的异常,并通过自定义的异常处理类捕获这个异常并处理
    try{
        $testObj1 =new TestException(1);         //传1时,抛出自定义异常
        echo "********
";                     //这个语句不会被执行
    }catch(MyException $e){                      //这个catch区块中的代码将被执行
        echo "捕获自定义的异常:$e
";         
        $e->customFunction();                   
    }catch(Exception $e){                        //这个catch区块不会执行
        echo "捕获默认的异常:".$e->getMessage()."
";      
    }
    var_dump($testObj1);        //有异常产生,这个对象没有创建成功
 
    //示例2,抛出自内置的异常,并通过自定义的异常处理类捕获这个异常并处理
    try{
        $testObj2 =new TestException(2);         //传入2时,抛出内置异常
        echo "********
";                     //这个语句不会被执行
    }catch(MyException $e){                      //这个catch区块中的代码将被执行
        echo "捕获自定义的异常:$e
";         
        $e->customFunction();                   
    }catch(Exception $e){                        //这个catch区块不会执行
        echo "捕获默认的异常:".$e->getMessage()."
";      
    }
    var_dump($testObj2);        //有异常产生,这个对象没有创建成功
?>

在上面的代码中,可以使用两个异常处理类:一个是自定义的异常处理类MyException;另一个则是PHP中内置的异常处理类Exception。分别在try区块中创建测试类TestException的对象,并根据构造方法中提供的不同数字参数,抛出自定义异常类对象、内置的异常类对象和不抛出任何异常的情况,跳转到对应的catch区块中执行。如果没有异常发生,则不会进入任何一个catch块中执行,测试类TestException的对象创建成功

希望本文所述对大家的php程序设计有所帮助。

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
3 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
1666
14
PHP Tutorial
1273
29
C# Tutorial
1253
24
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: 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 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.

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.

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 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: 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 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