|
class FileExistsException extends Exception{}
//用於處理檔案不存在異常的類
class FileOpenException extends Exception{}
//用於處理檔案不可讀異常的類
$path = "D://in.txt";
try
{
file_open($path);
}
catch(FileExistsException $e)
//如果產生FileExistsException異常則提示使用者確認檔案位置
{
echo "程式在運行過程中發生了異常:".$e->getMessage()."/n";
echo "請確認檔案位置。";
}
catch(FileOpenException $e)
//如果產生FileOpenException異常則提示使用者確認檔案的可讀性
{
echo "程式在運行過程中發生了異常:".$e->getMessage()."/n";
echo "請確認檔案的可讀性。";
}
catch(Exception $e)
{
echo "[未知異常]";
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)
{
try
{
if(!file_exists($path))
{
throw new FileExistsException("檔案無法找到", 1);
}
if(!fopen($path, "r"))
{
throw new FileOpenException("檔案無法開啟", 2);
}
}
catch(Exception $e) //捕獲異常
{
echo "file_open函數在運行過程中出現異常";
throw $e; //重擲異常
}
}
?>
|