


Exception capture can be easily added in many current IDE tools using shortcut keys to prevent users from seeing errors they cannot understand or even crashing inexplicably, resulting in a poor user experience. Even displaying a friendly crash prompt is much better than directly displaying error:xxxx xxxxxxxxx. This article will introduce in detail how PHP throws exceptions and catches specific types of exceptions. I hope it will be helpful to everyone.
What is an exception?
PHP 5 provides a new object-oriented error handling method.
Exception handling is used to change the normal flow of the script when a specified error (exception) situation occurs. This situation is called an exception.
When an exception is triggered, what usually happens is:
The current code state is saved
Code execution Switched to a predefined exception handler function
Depending on the situation, the handler may restart code execution from the saved code state, terminate script execution, or continue script execution from another location in the code
We will show different error handling methods:
Basic use of exceptions
Creating custom Exception handler
Multiple exceptions
Re-throw exception
Set top-level exception handler
php throw The ultimate goal of throwing exceptions and catching specific types of exceptions is to provide corresponding solutions so that the code can continue to run.
The test environment of this article: PHP5.5.36 Safari 9.1.2
1 <?php 2 header("content-type:text/html; charset=utf-8"); 3 /** 4 * 包裹重量异常 5 */ 6 class HeavyParcelException extends Exception {} 7 8 /** 9 * 包裹类 10 */ 11 class Parcel { 12 13 /** 14 * 包裹寄送目的地地址 15 */ 16 public $address; 17 18 /** 19 * 包裹重量 20 */ 21 public $weight; 22 } 23 24 /** 25 * 派送员 26 */ 27 class Courier { 28 29 /** 30 * 运送 31 */ 32 public function ship(Parcel $parcel) { 33 //check we have an address 34 //如果包裹的目的地为空 35 if(empty($parcel->address)) { 36 throw new Exception('address not Specified(未填写地址)!'); 37 } 38 39 //check the weight 40 //如果重量超过5 41 if($parcel->weight > 5) { 42 throw new HeavyParcelException('Parcel exceeds courier limit(包裹超过运送上限)!'); 43 } 44 45 //otherwise we're coll 46 return true; 47 } 48 } 49 50 $myCourier = new Courier(); 51 $parcel = new Parcel(); 52 //add the address if we have it 为了测试这里不填写地址 53 $parcel->weight = 7; 54 try { 55 $myCourier->ship($parcel); 56 echo "parcel shipped"; 57 } catch (HeavyParcelException $e) {//捕获HeavyParcelException 不写这个异常的类型名字,就跑到普通Exception抛出去了 58 echo "Parcel weight error(重量错误): " . $e->getMessage(); 59 //redirect them to choose another courier 60 } catch (Exception $e) { 61 echo "Someting went wrong(地址错误): " . $e->getMessage(); 62 //exit so we don't try to proceed any further 63 exit; 64 } 65 echo '<br/>'; 66 $a = 123; 67 echo $a;
The code execution sequence starting from line 54:
55 >
32 >
35(The ship method first checks that the address is empty, and Exception
will be thrown here instead of HeavyParcelException
) on line 57 >
60(caughtException
) >
616263 Output address errorexit
; Lines 65 to 67 will not be output.
Tips:
I feel that the most important thing in this area is to figure out the order of code execution. Write a few paragraphs, then revise them and run them.
1. The order of capture depends on which type of Exception
is throw
in the code in try
, and then ## The order in #catch.
HeavyParcelException cannot be written incorrectly, or there will be problems if you write
Exception. You can try it yourself.
HeavyParcelException111, then the weight error will be captured in its parent class object on line 60. This is not what we want.
Exception, an address error will be thrown, but the
catch originally responsible for the weight will be captured. This is not what we want either.
Related recommendations:
Customization of PHP exception handler
How does PHP implement image recognition
How does PHP implement process locks and multi-processes
The above is the detailed content of Detailed explanation of catching specific types of exceptions in php. For more information, please follow other related articles on the PHP Chinese website!

php把负数转为正整数的方法:1、使用abs()函数将负数转为正数,使用intval()函数对正数取整,转为正整数,语法“intval(abs($number))”;2、利用“~”位运算符将负数取反加一,语法“~$number + 1”。

实现方法:1、使用“sleep(延迟秒数)”语句,可延迟执行函数若干秒;2、使用“time_nanosleep(延迟秒数,延迟纳秒数)”语句,可延迟执行函数若干秒和纳秒;3、使用“time_sleep_until(time()+7)”语句。

php除以100保留两位小数的方法:1、利用“/”运算符进行除法运算,语法“数值 / 100”;2、使用“number_format(除法结果, 2)”或“sprintf("%.2f",除法结果)”语句进行四舍五入的处理值,并保留两位小数。

判断方法:1、使用“strtotime("年-月-日")”语句将给定的年月日转换为时间戳格式;2、用“date("z",时间戳)+1”语句计算指定时间戳是一年的第几天。date()返回的天数是从0开始计算的,因此真实天数需要在此基础上加1。

php字符串有下标。在PHP中,下标不仅可以应用于数组和对象,还可应用于字符串,利用字符串的下标和中括号“[]”可以访问指定索引位置的字符,并对该字符进行读写,语法“字符串名[下标值]”;字符串的下标值(索引值)只能是整数类型,起始值为0。

方法:1、用“str_replace(" ","其他字符",$str)”语句,可将nbsp符替换为其他字符;2、用“preg_replace("/(\s|\ \;||\xc2\xa0)/","其他字符",$str)”语句。

php判断有没有小数点的方法:1、使用“strpos(数字字符串,'.')”语法,如果返回小数点在字符串中第一次出现的位置,则有小数点;2、使用“strrpos(数字字符串,'.')”语句,如果返回小数点在字符串中最后一次出现的位置,则有。

在php中,可以使用substr()函数来读取字符串后几个字符,只需要将该函数的第二个参数设置为负值,第三个参数省略即可;语法为“substr(字符串,-n)”,表示读取从字符串结尾处向前数第n个字符开始,直到字符串结尾的全部字符。


Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

AI Hentai Generator
Generate AI Hentai for free.

Hot Article

Hot Tools

SAP NetWeaver Server Adapter for Eclipse
Integrate Eclipse with SAP NetWeaver application server.

EditPlus Chinese cracked version
Small size, syntax highlighting, does not support code prompt function

Dreamweaver Mac version
Visual web development tools

Notepad++7.3.1
Easy-to-use and free code editor

VSCode Windows 64-bit Download
A free and powerful IDE editor launched by Microsoft
