什么是 PHP 中的异常处理?
异常是在程序执行期间出现的问题。在程序执行过程中,当发生异常时,语句后面的代码将不会执行,PHP 将尝试查找第一个匹配的 catch 块。如果未捕获异常,则会发出带有“未捕获异常”的 PHP 致命错误。
语法
try {
print "this is our try block";
throw new Exception();
}catch (Exception $e) {
print "something went wrong, caught yah! n";
}finally {
print "this part is always executed";
}示例
<?php
function printdata($data) {
try {
//If var is six then only if will be executed
if($data == 6) {
// If var is zero then only exception is thrown
throw new Exception('Number is six.');
echo "
After throw (It will never be executed)";
}
}
// When Exception has been thrown by try block
catch(Exception $e){
echo "
Exception Caught", $e->getMessage();
}
//this block code will always executed.
finally{
echo "
Final block will be always executed";
}
}
// Exception will not be rised here
printdata(0);
// Exception will be rised
printdata(6);
?>输出
Final block will be always executed Exception CaughtNumber is six. Final block will be always executed
备注
要处理异常,程序代码必须在 try 块内。每个 try 必须至少有一个相应的 catch 块。可以使用多个 catch 块来捕获不同类的异常。
广告
数据结构
网络
RDBMS
操作系统
Java
iOS
HTML
CSS
Android
Python
C 编程
C++
C#
MongoDB
MySQL
Javascript
PHP