1 首先是try,catch
<?php
$path = "D:////in.txt";
try //檢測異常
{
file_open($path);
}
catch(Exception $e) //捕獲異常
{
echo $e->getMessage();
}
function file_open($path)
{
if(!file_exists($path)) //如果文件無法找到,拋出異常對象
{
throw new Exception("文件無法找到", 1);
}
if(!fopen($path, "r")) //如果文件無法打開,拋出異常對象
{
throw new Exception("文件無法打開", 2);
}
}
?>
注意用$e->getMessage()輸出異常信息.
2 輸出異常完整信息
<?php
$path = "D:////in.txt";
try
{
file_open($path); //嘗試打開文件
}
catch(Exception $e)
{
echo "異常信息:".$e->getMessage()."//n"; //返回用戶自定義的異常信息
echo "異常代碼:".$e->getCode()."//n"; //返回用戶自定義的異常代碼
echo "文件名:".$e->getFile()."//n"; //返回發生異常的PHP程序文件名
echo "異常代碼所在行".$e->getLine()."//n"; //返回發生異常的代碼所在行的行號
echo "傳遞路線:";
print_r($e->getTrace()); //以數組形式返回跟蹤異常每一步傳遞的路線
echo $e->getTraceAsString(); //返回格式化成字符串的getTrace函數信息
}
function file_open($path)
{
if(!file_exists($path)) //如果文件不存在,則拋出錯誤
{
throw new Exception("文件無法找到", 1);
}
if(!fopen($path, "r"))
{
throw new Exception("文件無法打開", 2);
}
}
?>
新聞熱點
疑難解答