Home Backend Development PHP Tutorial Detailed explanation of the definition and use of exception handling in PHP

Detailed explanation of the definition and use of exception handling in PHP

Jul 26, 2017 pm 02:56 PM
php definition use

This article mainly introduces the definition and usage of PHP exception handling. It analyzes the definition, usage and related precautions of PHP exception handling in more detail. Friends in need can refer to the following

Examples of this article Understand the definition and usage of PHP exception handling. Share it with everyone for your reference, the details are as follows:


<?php
//php5提供了基本的异常处理类,可直接使用 ,不需要自己再定义
// class Exception
// {
// protected $message = &#39;Unknown exception&#39;; // 异常信息
// 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(); // 可输出的字符串
// }
?>
Copy after login


<?php
//定义一个顶级异常处理
function my_exception($e){
  echo "我是顶级异常处理".$e->getMessage();
}
//修改默认的顶级异常处理函数(器)
set_exception_handler("my_exception");
//我们使用异常机制
try{
  addUser("shunping");
  updateUser("xiaoming1");
}
//catch用来 捕获异常, Exception 是异常类(是php定义好一个类)
catch(Exception $e){
  //返回异常信息
  echo "返回异常信息(失败信息) =".$e->getMessage()."<br/>";
  echo "返回异常代码 =".$e->getCode()."<br/>";
  echo "返回发生异常的文件名 =".$e->getFile()."<br/>";
  echo "返回发生异常的代码行号 =".$e->getLine()."<br/>";
  //echo " =".$e->getTrace()."<br/>"; // backtrace() 数组
  //可以继续抛出,这时将会启动php默认的异常处理器来处理
  //你也可以自己定义一个顶级异常处理器,对其进行处理
  throw $e;
}
function addUser($username){
  if($username=="shunping"){
    //添加ok
    echo "ok1";
  }else{
    //添加error
    //抛出异常.
    throw new Exception("添加失败");
  }
}
function updateUser($username){
  if($username=="xiaoming"){
    //正常修改
    echo "ok2";
  }else{
    //平抛出异常
    throw new Exception("修改失败");
  }
}
?>
Copy after login

Precautions for abnormal use:

Through the above case, we can see that using this method


try{
    //代码
}catch(Exception $e){
    //对异常处理
}
Copy after login

can control errors more effectively. Therefore, it is widely used in development.

1. When an exception is caught, the subsequent code in the try{} block will not continue to execute.
2. If an exception occurs but you do not catch it, a will be prompted. Uncaught Exception.(System.)<br/>3. When catching an exception, you can handle it or not. If you don’t handle it, you can
throw new Exception("information");

4. You can customize the exception class


class MyException extends Exception {
}
Copy after login

5. Use multiple catch code blocks to catch different types of exceptions


try{
    //代码....
  //第一句话
  //第二句话
}catch(PDOException $e){
    //
}catch(Exception $e){
|
}
Copy after login

6. You can also simply use Exception to capture

Code description:


<?php
    //定义了一个异常
    class MyException1 extends Exception{
    }
    class MyException2 extends Exception{
    }
    function A(){
       throw new MyException1("a");
    }
    function B(){
       throw new MyException2("b")
    }
    function C(){
       try{
           A();//抛出MyException1
           B();//抛出MyException2
       }catch(Exception1 $e1){
           $e1->getMessage();
       }catch(Exception2 $e2){
           $e2->getMesage();
       }
    }
?>
Copy after login

Exception rules

Code that requires exception handling should be placed within a try code block to catch potential exceptions.
Each try or throw code block must have at least one corresponding catch code block.
Use multiple catch code blocks to catch different types of exceptions.
Exceptions can be thrown (thrown again) in the catch code block within the try code block.
In short: if an exception is thrown, you must catch it. Or use a top-level exception handler.
If it is not thrown, even if there is an exception, it will not be caught or processed

The above is the detailed content of Detailed explanation of the definition and use of exception handling in PHP. For more information, please follow other related articles on the PHP Chinese website!

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)
2 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Hello Kitty Island Adventure: How To Get Giant Seeds
1 months ago By 尊渡假赌尊渡假赌尊渡假赌
Two Point Museum: All Exhibits And Where To Find Them
1 months 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)

CakePHP Project Configuration CakePHP Project Configuration Sep 10, 2024 pm 05:25 PM

In this chapter, we will understand the Environment Variables, General Configuration, Database Configuration and Email Configuration in CakePHP.

PHP 8.4 Installation and Upgrade guide for Ubuntu and Debian PHP 8.4 Installation and Upgrade guide for Ubuntu and Debian Dec 24, 2024 pm 04:42 PM

PHP 8.4 brings several new features, security improvements, and performance improvements with healthy amounts of feature deprecations and removals. This guide explains how to install PHP 8.4 or upgrade to PHP 8.4 on Ubuntu, Debian, or their derivati

CakePHP Date and Time CakePHP Date and Time Sep 10, 2024 pm 05:27 PM

To work with date and time in cakephp4, we are going to make use of the available FrozenTime class.

CakePHP File upload CakePHP File upload Sep 10, 2024 pm 05:27 PM

To work on file upload we are going to use the form helper. Here, is an example for file upload.

CakePHP Routing CakePHP Routing Sep 10, 2024 pm 05:25 PM

In this chapter, we are going to learn the following topics related to routing ?

Discuss CakePHP Discuss CakePHP Sep 10, 2024 pm 05:28 PM

CakePHP is an open-source framework for PHP. It is intended to make developing, deploying and maintaining applications much easier. CakePHP is based on a MVC-like architecture that is both powerful and easy to grasp. Models, Views, and Controllers gu

CakePHP Creating Validators CakePHP Creating Validators Sep 10, 2024 pm 05:26 PM

Validator can be created by adding the following two lines in the controller.

CakePHP Working with Database CakePHP Working with Database Sep 10, 2024 pm 05:25 PM

Working with database in CakePHP is very easy. We will understand the CRUD (Create, Read, Update, Delete) operations in this chapter.

See all articles