减肥早餐适合吃什么| 抑郁症为什么会想死| 全科医学科是什么科| 飞五行属什么| 猫眼是什么| 冰醋酸是什么| 脾虚气滞吃什么中成药| 流火是什么原因造成的| 但闻人语响的但是什么意思| 三羊念什么字| 检查肺结节挂什么科| 今年50岁属什么| 脾大是什么原因引起的| 趋光性是什么意思| 生活防水是什么意思| 中暑喝什么好| 人体乳头瘤病毒是什么| 13颗珠子的手串什么意思| 牙龈肿痛吃什么中成药| 结膜囊在眼睛什么位置| 梦见蝴蝶是什么意思| 贼不走空什么意思| oa是什么意思| 白矾是什么东西| 司令是什么意思| 梦到高考是什么意思| 附件炎吃什么药好| 脚后跟骨头疼是什么原因| 祈字五行属什么| 手脚麻是什么原因| 叶字五行属什么| 经期喝酒会有什么危害| 吗丁啉是什么药| 直肠炎是什么原因引起| 高粱是什么| 姨妈期不能吃什么| surprise是什么意思| 没经验开什么店最简单| 姑姐是什么意思| 谌读什么| 近视吃什么改善视力| 肝素是什么| 睡觉爱流口水是什么原因| 漫威是什么意思| 阳虚吃什么中药| 感冒吃什么水果| 画是什么生肖| 阴阳脸是什么意思| 勾践属什么生肖| 3月27日什么星座| 房颤是什么| 甲功三项是检查什么| 虾米吃什么| 左肋骨下方是什么器官| 6月30是什么星座| 肾属于什么科| 梦见大便是什么预兆| 眼圈黑是什么原因| 康复新液是什么做的| 拾人牙慧的意思是什么| 珠光宝气是什么生肖| 夫妻备孕检查挂什么科| 神器积分换什么最划算| 456是什么意思| 火车和高铁有什么区别| 梦见女婴儿是什么意思| 痛风什么蔬菜不能吃| 处女座和什么座最配| 王字旁和什么有关| 肚子疼呕吐是什么原因引起的| 世界上最小的长度单位是什么| 喜字五行属什么| 拉肚子发烧吃什么药| 皮肤偏黄适合穿什么颜色的衣服| 肠炎吃什么药| 心衰是什么意思| 查询电话号码拨打什么| 三七有什么功效和作用| 什么意思啊| 心眼多是什么意思| 今年7岁属什么生肖| 日月星辰下一句是什么| 歆字取名什么寓意| 六味地黄丸什么时候吃最好| 耳石症眩晕吃什么药| 宝宝什么意思| 总是放屁是什么原因| 六三年属什么生肖| 清明为什么插柳枝| 嗤之以鼻是什么意思| 根尖周炎吃什么药| mint什么颜色| 灰喜鹊吃什么| 水乳是什么| 等着我为什么停播了| 品牌是什么| 尿路感染吃什么中药| 蒟蒻是什么| 不堪入目是什么意思| 母亲是o型血孩子是什么血型| 猫代表什么象征意义| 为什么掉头发很厉害| 为什么德牧不能打| 心烦意乱是什么意思| 蔡英文是什么党派| 例假来的是黑色的是什么原因| mh是什么单位| 艾拉是什么药| 胃胀吃点什么药| 黄痰吃什么药最好| 突然不硬是什么原因| 什么是变应性鼻炎| 鼻塞用什么药| 北京大裤衩建筑叫什么| 痛风不能吃什么蔬菜| 很黄很暴力是什么意思| 红眼病吃什么药| 手癣用什么药膏效果好| tnt什么意思| 有什么症状| 白兰地是什么酒| 手掌痒是什么原因| 卟是什么意思| 光影什么| 歧途什么意思| 抑郁症是什么原因造成| 竹棉和纯棉有什么区别| 外感发热什么意思| 梦到前夫什么意思| 双抗是什么药| 甲状腺结节吃什么食物好| 大便黑色是什么问题| 水为什么会结冰| 空腹喝酒有什么危害| 言字旁可念什么| 舌根放血有什么好处| 手术后能吃什么| 回流是什么意思| 鲜卑人是现在的什么人| 放的屁很臭是什么原因| 肚脐右边疼是什么原因| 口干口苦吃什么药最好| 喝水呛咳是什么原因| 梦到钓鱼是什么意思| 梦见自己生个女孩是什么意思| 冒失是什么意思| 桑黄是什么树上长出来的| 败血症吃什么药| 肚子疼是什么原因一阵一阵的| 风采是什么意思| 超声心动图检查什么| 有什么好| 正月二十九是什么星座| 肚子胀痛什么原因| 蔓越莓是什么水果| 咽喉肿痛吃什么消炎药| 县级市市长什么级别| 9价疫苗适合什么年龄人打| p0s是什么意思| 偏头痛看什么科| 菠萝什么季节成熟| 刷酸是什么意思| 天长地久是什么生肖| 什么药化痰效果最好| 氧化氢是什么| 五福是什么生肖| 减肥吃什么零食| 什么茶去火| 小腿怕冷是什么原因| 晚上睡觉脚底发热是什么原因| 心肌酶是检查什么的| 正常舌头是什么颜色| 手上的月牙代表什么意思| 为什么虾煮熟了会变红| dior什么意思| 尿糖是什么意思| 线雕是什么| 什么叫培根| 喝盐水有什么作用和功效| 月经来的少是什么原因| 早上9点多是什么时辰| 驾驶证和行驶证有什么区别| 口诀是什么意思| 修心是什么意思| 开眼镜店需要什么设备| 尴尬什么意思| 核医学科是检查什么的| 63岁属什么生肖| 点灯是什么意思| 眼袋大是什么原因引起的| 补维生素吃什么好| 蜱虫咬人后有什么症状| 日间病房是什么意思| 上校相当于政府什么官| 颧骨长斑是什么原因| 小孩腰疼是什么原因引起的| 筋膜炎吃什么药| 口渴是什么原因| 脑瘫是什么意思| 手筋痛是什么原因| 口干舌燥喝水也不解渴是什么原因| 盥洗是什么意思| sahara是什么牌子| myp是什么意思| 做不好的梦预示着什么| 伊始什么意思| 大便带血是什么原因男| 什么是http| 埃及艳后叫什么| 闰月是什么意思| 上火牙龈肿痛吃什么药| 积液是什么原因造成的怎么治疗| 树膏皮是什么皮| 月经总推迟是什么原因| 什么是天葬| 什么球身上长毛| 下半夜咳嗽是什么原因| 轴位是什么| 为什么会晒黑| 荷花的花语是什么| 看淋巴挂什么科室| 需要透析的是什么病| 维生素c对身体有什么好处| 黄色是什么颜色组成的| 相手蟹吃什么| 社科院是干什么的| 盗墓笔记的结局是什么| 经常喝藕粉有什么好处| 石斛是什么东西| 怀孕去医院检查挂什么科| 多饮多尿可能是什么病| 凌迟是什么| 什么精神成语| 脚背肿是什么原因引起的| 腱鞘炎有什么症状| 苑字五行属什么| 头发不长是什么原因| pf是什么意思| 眼睛干涩用什么眼药水好| 喝最烈的酒下一句是什么| 孩子嗓子疼吃什么药| 4月19号是什么星座| 滞留是什么意思| 什么手机拍照效果最好| 吾子是什么意思| 狮子座的幸运色是什么| 为什么不能拜女娲娘娘| 高血脂不能吃什么| 为什么月亮是红色的| 未扪及是什么意思| 天兵神将是什么动物| 喝紫苏水有什么功效| 痞是什么意思| 手脚麻木吃什么药| 想改名字需要什么手续| 三月18号是什么星座的| 淋巴滤泡增生用什么药能彻底治愈| 飞机不能带什么东西| 什么之财| 大理有什么好玩的| 人为什么要喝酒| 四季花是什么花| 讽刺是什么意思| 南海龙王叫什么| 百度
PHP 8.5.0 Alpha 4 available for testing

平潭的逆袭 ——专访平潭综合实验区管委会主任许维泽

Table of Contents

百度 无锡著名长篇民歌《赵圣关》的女主人公林二姐,也实指是杭州临平人,该歌有多节描述临平运河段风光的唱词。

PHP has an exception model similar to that of other programming languages. An exception can be thrown, and caught ("catched") within PHP. Code may be surrounded in a try block, to facilitate the catching of potential exceptions. Each try must have at least one corresponding catch or finally block.

If an exception is thrown and its current function scope has no catch block, the exception will "bubble up" the call stack to the calling function until it finds a matching catch block. All finally blocks it encounters along the way will be executed. If the call stack is unwound all the way to the global scope without encountering a matching catch block, the program will terminate with a fatal error unless a global exception handler has been set.

The thrown object must be an instanceof Throwable. Trying to throw an object that is not will result in a PHP Fatal Error.

As of PHP 8.0.0, the throw keyword is an expression and may be used in any expression context. In prior versions it was a statement and was required to be on its own line.

catch

A catch block defines how to respond to a thrown exception. A catch block defines one or more types of exception or error it can handle, and optionally a variable to which to assign the exception. (The variable was required prior to PHP 8.0.0.) The first catch block a thrown exception or error encounters that matches the type of the thrown object will handle the object.

Multiple catch blocks can be used to catch different classes of exceptions. Normal execution (when no exception is thrown within the try block) will continue after that last catch block defined in sequence. Exceptions can be thrown (or re-thrown) within a catch block. If not, execution will continue after the catch block that was triggered.

When an exception is thrown, code following the statement will not be executed, and PHP will attempt to find the first matching catch block. If an exception is not caught, a PHP Fatal Error will be issued with an "Uncaught Exception ..." message, unless a handler has been defined with set_exception_handler().

As of PHP 7.1.0, a catch block may specify multiple exceptions using the pipe (|) character. This is useful for when different exceptions from different class hierarchies are handled the same.

As of PHP 8.0.0, the variable name for a caught exception is optional. If not specified, the catch block will still execute but will not have access to the thrown object.

finally

A finally block may also be specified after or instead of catch blocks. Code within the finally block will always be executed after the try and catch blocks, regardless of whether an exception has been thrown, and before normal execution resumes.

One notable interaction is between the finally block and a return statement. If a return statement is encountered inside either the try or the catch blocks, the finally block will still be executed. Moreover, the return statement is evaluated when encountered, but the result will be returned after the finally block is executed. Additionally, if the finally block also contains a return statement, the value from the finally block is returned.

Another notable interaction is between an exception thrown from within a try block, and an exception thrown from within a finally block. If both blocks throw an exception, then the exception thrown from the finally block will be the one that is propagated, and the exception thrown from the try block will be used as its previous exception.

Global exception handler

If an exception is allowed to bubble up to the global scope, it may be caught by a global exception handler if set. The set_exception_handler() function can set a function that will be called in place of a catch block if no other block is invoked. The effect is essentially the same as if the entire program were wrapped in a try-catch block with that function as the catch.

Notes

Note:

Internal PHP functions mainly use Error reporting, only modern Object-oriented extensions use exceptions. However, errors can be easily translated to exceptions with ErrorException. This technique only works with non-fatal errors, however.

Example #1 Converting error reporting to exceptions

<?php
function exceptions_error_handler($severity, $message, $filename, $lineno) {
throw new
ErrorException($message, 0, $severity, $filename, $lineno);
}

set_error_handler('exceptions_error_handler');
?>

Tip

The Standard PHP Library (SPL) provides a good number of built-in exceptions.

Examples

Example #2 Throwing an Exception

<?php
function inverse($x) {
if (!
$x) {
throw new
Exception('Division by zero.');
}
return
1/$x;
}

try {
echo
inverse(5) . "\n";
echo
inverse(0) . "\n";
} catch (
Exception $e) {
echo
'Caught exception: ', $e->getMessage(), "\n";
}

// Continue execution
echo "Hello World\n";
?>

The above example will output:

0.2
Caught exception: Division by zero.
Hello World

Example #3 Exception handling with a finally block

<?php
function inverse($x) {
if (!
$x) {
throw new
Exception('Division by zero.');
}
return
1/$x;
}

try {
echo
inverse(5) . "\n";
} catch (
Exception $e) {
echo
'Caught exception: ', $e->getMessage(), "\n";
} finally {
echo
"First finally.\n";
}

try {
echo
inverse(0) . "\n";
} catch (
Exception $e) {
echo
'Caught exception: ', $e->getMessage(), "\n";
} finally {
echo
"Second finally.\n";
}

// Continue execution
echo "Hello World\n";
?>

The above example will output:

0.2
First finally.
Caught exception: Division by zero.
Second finally.
Hello World

Example #4 Interaction between the finally block and return

<?php

function test() {
try {
throw new
Exception('foo');
} catch (
Exception $e) {
return
'catch';
} finally {
return
'finally';
}
}

echo
test();
?>

The above example will output:

finally

Example #5 Nested Exception

<?php

class MyException extends Exception { }

class
Test {
public function
testing() {
try {
try {
throw new
MyException('foo!');
} catch (
MyException $e) {
// rethrow it
throw $e;
}
} catch (
Exception $e) {
var_dump($e->getMessage());
}
}
}

$foo = new Test;
$foo->testing();

?>

The above example will output:

string(4) "foo!"

Example #6 Multi catch exception handling

<?php

class MyException extends Exception { }

class
MyOtherException extends Exception { }

class
Test {
public function
testing() {
try {
throw new
MyException();
} catch (
MyException | MyOtherException $e) {
var_dump(get_class($e));
}
}
}

$foo = new Test;
$foo->testing();

?>

The above example will output:

string(11) "MyException"

Example #7 Omitting the caught variable

Only permitted in PHP 8.0.0 and later.

<?php

class SpecificException extends Exception {}

function
test() {
throw new
SpecificException('Oopsie');
}

try {
test();
} catch (
SpecificException) {
print
"A SpecificException was thrown, but we don't care about the details.";
}
?>

The above example will output:

A SpecificException was thrown, but we don't care about the details.

Example #8 Throw as an expression

Only permitted in PHP 8.0.0 and later.

<?php

function test() {
do_something_risky() or throw new Exception('It did not work');
}

function
do_something_risky() {
return
false; // Simulate failure
}

try {
test();
} catch (
Exception $e) {
print
$e->getMessage();
}
?>

The above example will output:

It did not work

Example #9 Exception in try and in finally

<?php

try {
try {
throw new
Exception(message: 'Third', previous: new Exception('Fourth'));
} finally {
throw new
Exception(message: 'First', previous: new Exception('Second'));
}
} catch (
Exception $e) {
var_dump(
$e->getMessage(),
$e->getPrevious()->getMessage(),
$e->getPrevious()->getPrevious()->getMessage(),
$e->getPrevious()->getPrevious()->getPrevious()->getMessage(),
);
}

The above example will output:

string(5) "First"
string(6) "Second"
string(5) "Third"
string(6) "Fourth"
add a note

User Contributed Notes 13 notes

up
127
ask at nilpo dot com
16 years ago
If you intend on creating a lot of custom exceptions, you may find this code useful. I've created an interface and an abstract exception class that ensures that all parts of the built-in Exception class are preserved in child classes. It also properly pushes all information back to the parent constructor ensuring that nothing is lost. This allows you to quickly create new exceptions on the fly. It also overrides the default __toString method with a more thorough one.

<?php
interface IException
{
/* Protected methods inherited from Exception class */
public function getMessage(); // Exception message
public function getCode(); // User-defined Exception code
public function getFile(); // Source filename
public function getLine(); // Source line
public function getTrace(); // An array of the backtrace()
public function getTraceAsString(); // Formated string of trace

/* Overrideable methods inherited from Exception class */
public function __toString(); // formated string for display
public function __construct($message = null, $code = 0);
}

abstract class
CustomException extends Exception implements IException
{
protected
$message = 'Unknown exception'; // Exception message
private $string; // Unknown
protected $code = 0; // User-defined exception code
protected $file; // Source filename of exception
protected $line; // Source line of exception
private $trace; // Unknown

public function __construct($message = null, $code = 0)
{
if (!
$message) {
throw new
$this('Unknown '. get_class($this));
}
parent::__construct($message, $code);
}

public function
__toString()
{
return
get_class($this) . " '{$this->message}' in {$this->file}({$this->line})\n"
. "{$this->getTraceAsString()}";
}
}
?>

Now you can create new exceptions in one line:

<?php
class TestException extends CustomException {}
?>

Here's a test that shows that all information is properly preserved throughout the backtrace.

<?php
function exceptionTest()
{
try {
throw new
TestException();
}
catch (
TestException $e) {
echo
"Caught TestException ('{$e->getMessage()}')\n{$e}\n";
}
catch (
Exception $e) {
echo
"Caught Exception ('{$e->getMessage()}')\n{$e}\n";
}
}

echo
'<pre>' . exceptionTest() . '</pre>';
?>

Here's a sample output:

Caught TestException ('Unknown TestException')
TestException 'Unknown TestException' in C:\xampp\htdocs\CustomException\CustomException.php(31)
#0 C:\xampp\htdocs\CustomException\ExceptionTest.php(19): CustomException->__construct()
#1 C:\xampp\htdocs\CustomException\ExceptionTest.php(43): exceptionTest()
#2 {main}
up
78
Johan
14 years ago
Custom error handling on entire pages can avoid half rendered pages for the users:

<?php
ob_start
();
try {
/*contains all page logic
and throws error if needed*/
...
} catch (
Exception $e) {
ob_end_clean();
displayErrorPage($e->getMessage());
}
?>
up
11
tianyiw at vip dot qq dot com
1 year ago
Easy to understand `finally`.
<?php
try {
try {
echo
"before\n";
1 / 0;
echo
"after\n";
} finally {
echo
"finally\n";
}
} catch (
\Throwable) {
echo
"exception\n";
}
?>
# Print:
before
finally
exception
up
7
jlherren
1 year ago
As noted elsewhere, throwing an exception from the `finally` block will replace a previously thrown exception. But the original exception is magically available from the new exception's `getPrevious()`.

<?php
try {
try {
throw new
RuntimeException('Exception A');
} finally {
throw new
RuntimeException('Exception B');
}
}
catch (
Throwable $exception) {
echo
$exception->getMessage(), "\n";
// 'previous' is magically available!
echo $exception->getPrevious()->getMessage(), "\n";
}
?>

Will print:

Exception B
Exception A
up
30
Edu
12 years ago
The "finally" block can change the exception that has been throw by the catch block.

<?php
try{
try {
throw new
\Exception("Hello");
} catch(
\Exception $e) {
echo
$e->getMessage()." catch in\n";
throw
$e;
} finally {
echo
$e->getMessage()." finally \n";
throw new
\Exception("Bye");
}
} catch (
\Exception $e) {
echo
$e->getMessage()." catch out\n";
}
?>

The output is:

Hello catch in
Hello finally
Bye catch out
up
24
Shot (Piotr Szotkowski)
16 years ago
‘Normal execution (when no exception is thrown within the try block, *or when a catch matching the thrown exception’s class is not present*) will continue after that last catch block defined in sequence.’

‘If an exception is not caught, a PHP Fatal Error will be issued with an “Uncaught Exception …” message, unless a handler has been defined with set_exception_handler().’

These two sentences seem a bit contradicting about what happens ‘when a catch matching the thrown exception’s class is not present’ (and the second sentence is actually correct).
up
14
christof+php[AT]insypro.com
8 years ago
In case your E_WARNING type of errors aren't catchable with try/catch you can change them to another type of error like this:

<?php
set_error_handler
(function($errno, $errstr, $errfile, $errline){
if(
$errno === E_WARNING){
// make it more serious than a warning so it can be caught
trigger_error($errstr, E_ERROR);
return
true;
} else {
// fallback to default php error handler
return false;
}
});

try {
// code that might result in a E_WARNING
} catch(Exception $e){
// code to handle the E_WARNING (it's actually changed to E_ERROR at this point)
} finally {
restore_error_handler();
}
?>
up
15
daviddlowe dot flimm at gmail dot com
7 years ago
Starting in PHP 7, the classes Exception and Error both implement the Throwable interface. This means, if you want to catch both Error instances and Exception instances, you should catch Throwable objects, like this:

<?php

try {
throw new
Error( "foobar" );
// or:
// throw new Exception( "foobar" );
}
catch (
Throwable $e) {
var_export( $e );
}

?>
up
16
Simo
10 years ago
#3 is not a good example. inverse("0a") would not be caught since (bool) "0a" returns true, yet 1/"0a" casts the string to integer zero and attempts to perform the calculation.
up
12
mlaopane at gmail dot com
7 years ago
<?php

/**
* You can catch exceptions thrown in a deep level function
*/

function employee()
{
throw new
\Exception("I am just an employee !");
}

function
manager()
{
employee();
}

function
boss()
{
try {
manager();
} catch (
\Exception $e) {
echo
$e->getMessage();
}
}

boss(); // output: "I am just an employee !"
up
17
telefoontoestel at nospam dot org
11 years ago
When using finally keep in mind that when a exit/die statement is used in the catch block it will NOT go through the finally block.

<?php
try {
echo
"try block<br />";
throw new
Exception("test");
} catch (
Exception $ex) {
echo
"catch block<br />";
} finally {
echo
"finally block<br />";
}

// try block
// catch block
// finally block
?>

<?php
try {
echo
"try block<br />";
throw new
Exception("test");
} catch (
Exception $ex) {
echo
"catch block<br />";
exit(
1);
} finally {
echo
"finally block<br />";
}

// try block
// catch block
?>
up
10
Tom Polomsk
10 years ago
Contrary to the documentation it is possible in PHP 5.5 and higher use only try-finally blocks without any catch block.
up
9
Sawsan
13 years ago
the following is an example of a re-thrown exception and the using of getPrevious function:

<?php

$name
= "Name";

//check if the name contains only letters, and does not contain the word name

try
{
try
{
if (
preg_match('/[^a-z]/i', $name))
{
throw new
Exception("$name contains character other than a-z A-Z");
}
if(
strpos(strtolower($name), 'name') !== FALSE)
{
throw new
Exception("$name contains the word name");
}
echo
"The Name is valid";
}
catch(
Exception $e)
{
throw new
Exception("insert name again",0,$e);
}
}

catch (
Exception $e)
{
if (
$e->getPrevious())
{
echo
"The Previous Exception is: ".$e->getPrevious()->getMessage()."<br/>";
}
echo
"The Exception is: ".$e->getMessage()."<br/>";
}

?>
To Top
五行中什么生木 断眉有什么说法 什么是回迁房 山楂和什么一起泡水喝 急性胃肠炎用什么药
湿气是什么东西 四月二十一是什么星座 负离子什么意思 98年属什么 518是什么星座
嘴唇一圈发黑是什么原因造成的 山药炖什么好吃 血压低吃什么补得最快 烁字五行属什么 月亮的肚子指的是什么
4月24号是什么星座 猴年马月什么意思 炸腮有什么症状 夜卧早起是什么意思 天门冬氨酸氨基转移酶是什么
石钟乳是什么意思hcv8jop6ns7r.cn 儿童肚子痛挂什么科hcv8jop5ns4r.cn 退休工资什么时候补发hcv8jop4ns7r.cn 懒散是什么意思baiqunet.com 高岭土是什么hcv8jop1ns2r.cn
脑电图轻度异常什么病hcv8jop6ns8r.cn 排卵期出血是什么原因wuhaiwuya.com 济公属什么生肖的hcv8jop7ns0r.cn 梦见好多猫是什么意思hcv7jop4ns5r.cn 黄色裤子配什么上衣好看hcv9jop3ns3r.cn
孕妇吃什么鱼好hcv9jop8ns0r.cn 酒花浸膏是什么hcv9jop1ns5r.cn hr过高是什么意思hcv8jop7ns0r.cn 40不惑什么意思onlinewuye.com 再接再励是什么意思hcv8jop8ns7r.cn
9月25号什么星座hcv8jop5ns3r.cn 游乐场都有什么项目hcv7jop7ns3r.cn 端午节吃什么食物hcv8jop4ns4r.cn 市公安局长什么级别hcv8jop5ns2r.cn 吃生南瓜子有什么好处dajiketang.com
百度