php 錯誤處理與異常處理方法與實例教程
來源:程序員人生 發(fā)布時間:2014-02-10 20:11:31 閱讀次數(shù):3779次
在程序開發(fā)中,錯誤處理這一塊是非常重要的,今天本文章就來告訴他關(guān)于在php開發(fā)中,錯誤處理函數(shù)并且舉例說明錯誤處理的重要性。
1、內(nèi)置異常處理類、2、捕獲并處理異常的示例、3、exception類的成員函數(shù)getmessage()、4、exception類的成員函數(shù)getfile()、5、exception類的成員函數(shù)getline()、6、顯示警告或錯誤信息、7、自定義錯誤處理函數(shù)。
1,內(nèi)置異常處理類
- class exception
- {
- protected $message = 'unknown exception';
- protected $code = 0;
- protected $file;
- protected $line;
- function __construct($message = null, $code = 0);
- final function getmessage();
- final function getcode();
- final function getfile();
- final function getline();
- final function gettrace();
- final function gettraceasstring();
- function __tostring();
- }
2、捕獲并處理異常的示例
- try
- {
- $error = '拋出異常信息,并且跳出try塊<br/>';
- if(is_dir('./test'))
- {
- echo '檢測到../ch16是一個目錄';
- echo '<br/>';
- echo '可能繼續(xù)做其他一些操作';
- echo '<br/>';
- echo '....';
- echo '<br/>';
- }
- else
- {
- throw new exception($error,12345);
- }
- echo '上面throw異常的話,這行代碼不會執(zhí)行,轉(zhuǎn)而執(zhí)行catch塊<br/>';
- }
- catch(exception $e)
- {
- echo '捕獲異常: ' . $e->getmessage() . "<br/>錯誤代碼:" . $e->getcode().'<br/>';
- echo '<br/>';
- }
- echo '繼續(xù)執(zhí)行';
3、exception類的成員函數(shù)getmessage()
- $file = './test/readme.txt';
- try
- {
- if(is_dir($file))
- {
- echo '檢測到目錄';
- }
- else
- {
-
- throw new exception('未找到該目錄或文件');
- }
- }
- catch(exception $e)
- {
- echo '捕獲異常: ' . $e->getmessage();
- echo '<br/>===============================';
- echo '<br/>';
- }
- echo '程序執(zhí)行完畢';
4、exception類的成員函數(shù)getfile()
- $file = './test/readme.txt';
- try
- {
- if(is_dir($file))
- {
- echo '檢測到目錄';
- }
- else
- {
-
- throw new exception('未找到該目錄或文件');
- }
- }
- catch(exception $e)
- {
- echo '捕獲異常: ' . $e->getmessage();
- echo '<br/><br/>';
- echo '錯誤所在文件:'. $e->getfile();
- echo '<br/>===============================';
- echo '<br/>';
- }
- echo '程序執(zhí)行完畢';
-
5、exception類的成員函數(shù)getline()
- $file = './test/readme.txt';
- try
- {
- if(is_dir($file))
- {
- echo '檢測到目錄';
- }
- else
- {
-
- throw new exception('未找到該目錄或文件');
- }
- }
- catch(exception $e)
- {
- echo '捕獲異常: ' . $e->getmessage();
- echo '<br/><br/>';
- echo '錯誤所在文件:'. $e->getfile();
- echo '<br/><br/>';
- echo '錯誤所在行號:'. $e->getline();
- echo '<br/>===============================';
- echo '<br/>';
- }
- echo '程序執(zhí)行完畢';
6、顯示警告或錯誤信息
- error_reporting(e_warning | e_error);
- echo $uvar;
- callfunc();
-
- set_error_handler('myhandler');
- function myhandler($code, $msg, $file, $line)
- {
- echo "<br/>";
- echo "程序 <b>$file</b> 執(zhí)行過程中,在第 <b>$line</b> 行,產(chǎn)生一個錯誤。";
- echo "<br/>";
- echo "錯誤代碼為:<b>$code</b>, 錯誤的原因是: <b>$msg</b>";
- }
- echo $uvar;
生活不易,碼農(nóng)辛苦
如果您覺得本網(wǎng)站對您的學(xué)習(xí)有所幫助,可以手機(jī)掃描二維碼進(jìn)行捐贈