Home php教程 php手册 php中的错误异常处理

php中的错误异常处理

Jun 06, 2016 pm 07:56 PM
linux php deal with abnormal Community Enter mistake

欢迎进入Linux社区论坛,与200万技术人员互动交流 >>进入 在PHP5中添加了类似于其它语言的错误异常处理模块.在 PHP代码中所产生的异常可被 throw语句抛出并被 catch 语句捕获.需要进行异常处理的代码都必须放入 try 代码块内,以便捕获可能存在的异常.每一个

欢迎进入Linux社区论坛,与200万技术人员互动交流 >>进入

    在PHP5中添加了类似于其它语言的错误异常处理模块.在 PHP代码中所产生的异常可被 throw语句抛出并被 catch 语句捕获.需要进行异常处理的代码都必须放入 try 代码块内,以便捕获可能存在的异常.每一个 try 至少要有一个与之对应的 catch.使用多个 catch 可以捕获不同的类所产生的异常.当 try 代码块不再抛出异常或者找不到 catch 能匹配所抛出的异常时,PHP 代码就会在跳转到最后一个 catch 的后面继续执行.当然,PHP 允许在 catch 代码块内再次抛出(throw)异常.当一个异常被抛出时,其后(译者注:指抛出异常时所在的代码块)的代码将不会继续执行,而 PHP 就会尝试查找第一个能与之匹配的 catch.如果一个异常没有被捕获,而且又没用使用 set_exception_handler() 作相应的处理的话,那么 PHP 将会产生一个严重的错误,并且输出 Uncaught Exception ... (未捕获异常)的提示信息.

   

    /**

    * Exception.php

    * PHP5内置的异常类的属性与方法

    * 以下这段代码只为说明内置异常处理类的结构,它并不是一段有实际意义的可用代码.

    */

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

    }

    ?>

   

    /**

    * syntax .php

    */

    //语法结构以及分析

    //PHP有两种抛出异常的格式,如下

    //【1】try...catch...

    try {

    //实行可能有异常的操作,比如数据库错作,文件错作

    }catch (Exception $e){

    //打印错误信息

    }

    //【2】throw

    $message=‘我必须被运行在try{}块中****现异常的话我($message)将被返回(传递)给catch()里的异常对象的实例比如上面的$e';

    $code=123; //错误代码号,可在catch块中用$e->getCode();返回我的值 123,这样我就可以自定义错误代码号

    throw new Exception($message,$code);

    //学JAVA的注意,PHP异常处理没有throws

    ?>

   

    /**

    * Example.php

    */

    //两个实例掌握PHP异常处理

    //例【1】用 try...catch

    /* PDO连接mysql数据库,如果没看过PDO,先看下PDO的构造函数,要不跳过例1看例2 */

    $dsn = 'mysql:host=localhost;dbname=testdb';

    $user = 'dbuser';

    $password = 'dbpass';

    try {

    $dbh = new PDO($dsn, $user, $password); //创建数据库连接对象容易出现异常

    echo ’如果上面出现异常就不能显示我了‘;

    } catch (PDOException $e) {

    echo 'Connection failed: ' . $e->__toString();

    }

    ?>

   

    //例[2] try..cathc 和 throw一起用

    try {

    $error = ’我抛出异常信息,并且跳出try块‘;

    if(is_dir('./tests')){

    echo 'do sth.';

    }else{

    throw new Exception($error,12345);

    }

    echo ’上面有异常的话就轮不到我了!~
',“\n”;

    } catch (Exception $e) {

    echo ‘捕获异常: ', $e->getMessage(),$e->getCode(), “\n
”; //显示$error和123456

    }

    echo ’继续执行‘;

    ?>

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

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
WWE 2K25: How To Unlock Everything In MyRise
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)

Explain JSON Web Tokens (JWT) and their use case in PHP APIs. Explain JSON Web Tokens (JWT) and their use case in PHP APIs. Apr 05, 2025 am 12:04 AM

JWT is an open standard based on JSON, used to securely transmit information between parties, mainly for identity authentication and information exchange. 1. JWT consists of three parts: Header, Payload and Signature. 2. The working principle of JWT includes three steps: generating JWT, verifying JWT and parsing Payload. 3. When using JWT for authentication in PHP, JWT can be generated and verified, and user role and permission information can be included in advanced usage. 4. Common errors include signature verification failure, token expiration, and payload oversized. Debugging skills include using debugging tools and logging. 5. Performance optimization and best practices include using appropriate signature algorithms, setting validity periods reasonably,

Explain late static binding in PHP (static::). Explain late static binding in PHP (static::). Apr 03, 2025 am 12:04 AM

Static binding (static::) implements late static binding (LSB) in PHP, allowing calling classes to be referenced in static contexts rather than defining classes. 1) The parsing process is performed at runtime, 2) Look up the call class in the inheritance relationship, 3) It may bring performance overhead.

What are PHP magic methods (__construct, __destruct, __call, __get, __set, etc.) and provide use cases? What are PHP magic methods (__construct, __destruct, __call, __get, __set, etc.) and provide use cases? Apr 03, 2025 am 12:03 AM

What are the magic methods of PHP? PHP's magic methods include: 1.\_\_construct, used to initialize objects; 2.\_\_destruct, used to clean up resources; 3.\_\_call, handle non-existent method calls; 4.\_\_get, implement dynamic attribute access; 5.\_\_set, implement dynamic attribute settings. These methods are automatically called in certain situations, improving code flexibility and efficiency.

How to solve permission issues when using python --version command in Linux terminal? How to solve permission issues when using python --version command in Linux terminal? Apr 02, 2025 am 06:36 AM

Using python in Linux terminal...

Can the Python interpreter be deleted in Linux system? Can the Python interpreter be deleted in Linux system? Apr 02, 2025 am 07:00 AM

Regarding the problem of removing the Python interpreter that comes with Linux systems, many Linux distributions will preinstall the Python interpreter when installed, and it does not use the package manager...

Four ways to implement multithreading in C language Four ways to implement multithreading in C language Apr 03, 2025 pm 03:00 PM

Multithreading in the language can greatly improve program efficiency. There are four main ways to implement multithreading in C language: Create independent processes: Create multiple independently running processes, each process has its own memory space. Pseudo-multithreading: Create multiple execution streams in a process that share the same memory space and execute alternately. Multi-threaded library: Use multi-threaded libraries such as pthreads to create and manage threads, providing rich thread operation functions. Coroutine: A lightweight multi-threaded implementation that divides tasks into small subtasks and executes them in turn.

Explain the match expression (PHP 8 ) and how it differs from switch. Explain the match expression (PHP 8 ) and how it differs from switch. Apr 06, 2025 am 12:03 AM

In PHP8, match expressions are a new control structure that returns different results based on the value of the expression. 1) It is similar to a switch statement, but returns a value instead of an execution statement block. 2) The match expression is strictly compared (===), which improves security. 3) It avoids possible break omissions in switch statements and enhances the simplicity and readability of the code.

How to open web.xml How to open web.xml Apr 03, 2025 am 06:51 AM

To open a web.xml file, you can use the following methods: Use a text editor (such as Notepad or TextEdit) to edit commands using an integrated development environment (such as Eclipse or NetBeans) (Windows: notepad web.xml; Mac/Linux: open -a TextEdit web.xml)

See all articles