PHPでの例外処理
1. 異常とは何ですか?例外とエラーの違いは何ですか?
1. 例外: プログラムの動作は期待と一致せず、エラーは 2 つの異なる概念です。
2. 例外のスローとキャッチ
3. 複数の catch ブロックがある場合は、基本クラスを後で配置する必要があります。そうしないと、基本クラスは例外をキャッチした後、その例外をキャッチし続けません。
3. 最初にエラーが発生し、次に例外が発生するため、API を記述するときは、display_errors をオフにする必要があります
4. PHP の組み込み例外
error_reporting(-1);ini_set('display_errors','off');//pdo内置异常类try { $pdo = new PDO('mysql:host=localhost;dbname=mysql', 'brave', '123456'); var_dump($pdo); echo '<hr/>'; echo 'continue.......';} catch (Exception $e) { echo $e->getMessage();}echo 'this is a test.......';echo '<hr/>';//spl文件读写内置异常类try { $splObj = new SplFileObject('test.txt', 'r'); echo 'read file';} catch (RuntimeException $e) { echo $e->getMessage();}echo 'continue.......';echo '<hr/>';
2. 例外の基本構文構造
try { //需要进行异常处理的代码 throw语句抛出 } catch (PdoException $e) { try { throw语句抛出 } catch (Exception $e) { } } catch (FileException $e) { } catch (CustomException $e) { } //other code
3.例外クラス?
error_reporting(-1);ini_set('display_errors','off');class MyException extends Exception{ function __construct($message, $code=0) { parent::__construct($message, $code); } public function __toString(){ $message = "<h2>出现异常了,信息如下</h2>"; $message .="<p>".__CLASS__." [{$this->code}]:{$this->message}</p>"; return $message; } public function test(){ echo 'this is a test'; } public function stop(){ exit('script end..............<hr/>'); } //自定义其他方法}try { echo '出现异常了!'; throw new MyException("测试自定义异常!", 11);} catch (MyException $e) { echo $e->getMessage(); echo '<hr/>'; echo $e; echo '<hr/>'; $e->stop(); $e->test();}
4. ファイル例外クラスをカスタマイズします
error_reporting(-1);ini_set('display_errors','off');class FileException extends Exception { public function getDetails() { switch ($this->code) { case 0: return '没有提供文件!'; break; case 1: return '文件不存在!'." trace".$this->getTraceAsString().$this->getLine(); break; case 2: return '不是一个文件!'." trace".$this->getTraceAsString().$this->getLine(); break; case 3: return '文件不可写!'; break; case 4: return '非法文件的操作模式!'; break; case 5: return '数据写入失败!'; break; case 6: return '文件不能被关闭!'; break; default: return '非法!'; break; } }}class WriteData{ private $_message=''; private $_fp=null; public function __construct($filename=null, $mode='w'){ $this->_message="文件:{$filename} 模式:{$mode}"; if (empty($filename)) { throw new FileException($this->_message, 0); } if (!file_exists($filename)) { throw new FileException($this->_message, 1); } if (!is_file($filename)) { throw new FileException($this->_message, 2); } if (!is_writable($filename)) { throw new FileException($this->_message, 3); } if (!in_array($mode, array('w', 'w+', 'a', 'a+'))) { throw new FileException($this->_message, 4); } $this->_fp=fopen($filename, $mode); } /** * [write 写数据] * @param [type] $data [description] * @return [type] [description] */ public function write($data){ if (@!fwrite($this->_fp, $data.PHP_EOL)) { throw new FileException($this->_message, 5); } } /** * [close 关闭文件句柄] * @return [type] [description] */ public function close(){ if ($this->_fp) { if (@!fclose($this->_fp)) { throw new FileException($this->_message, 6); $this->_fp=null; } } } public function __destruct(){ $this->close(); }}try { $fp = new WriteData('test.txt', 'w'); $fp->write('this is a test'); $fp->close(); echo '数据写入成功!';} catch (FileException $e) { echo '出问题了:'.$e->getMessage().' 详细信息如下:'.$e->getDetails();}
5. オブザーバー パターンを使用して例外を処理します
- オブザーバーをコード内で動的に追加できます
/** * 观察(异常)的类, 可以在代码中动态的添加观察者 */ class Observable_Exception extends Exception { public static $_observers=array(); public static function attach(Exception_Observer $observer){ self::$_observers[]=$observer; } public function __construct($message=null, $code=0){ parent::__construct($message, $code); $this->notify(); } public function notify(){ foreach (self::$_observers as $observer) { $observer->update($this); } } }
2.監視 基本クラス 、各オブザーバー
/** * 观察者基类,用于规范每一个观察者 */ interface Exception_Observer{ //强制指定必须是我们规定的观察类 public function update(Observable_Exception $e); }
4. メール オブザーバー
/** * 定义日志观察者 */ class Logging_Exception_Observer implements Exception_Observer{ public $_filename='./log_exception.log'; public function __construct($filename=null){ if ($filename!==null && is_string($filename)) { $this->_filename=$filename; } } public function update(Observable_Exception $e){ $message="时间:".date('Y-m-d H:i:s').PHP_EOL; $message.="信息:".$e->getMessage().PHP_EOL; $message.="追踪信息:".$e->getTraceAsString().PHP_EOL; $message.="文件:".$e->getFile().PHP_EOL; $message.='行号:'.$e->getLine().PHP_EOL; error_log($message, 3, $this->_filename); } }
5. カスタム例外ハンドラー
/** * 定义邮件观察者 */ class Email_Exception_Observer implements Exception_Observer{ public $_email='732578448@qq.com'; public function __construct($email=null){ if ($email!==null && filter_var($email, FILTER_VALIDATE_EMAIL)) { $this->_email=$email; } } public function update(Observable_Exception $e){ $message="时间:".date('Y-m-d H:i:s').PHP_EOL; $message.="信息:".$e->getMessage().PHP_EOL; $message.="追踪信息:".$e->getTraceAsString().PHP_EOL; $message.="文件:".$e->getFile().PHP_EOL; $message.='行号:'.$e->getLine().PHP_EOL; error_log($message, 1, $this->_email); } }
6.
1. 目的 1. キャッチされなかった例外をすべて処理します
2. 目的 2. try catch に設定したすべての例外を処理します
3. カスタム例外処理関数
error_reporting(-1);ini_set('display_errors','off');//引入观察异常的类require 'Observable_Exception.php';//引入观察者基类require 'Exception_Observer.php';//引入日志观察者require 'Logging_Exception_Observer.php';//引入邮件观察者require 'Email_Exception_Observer.php';Observable_Exception::attach(new Logging_Exception_Observer());//自定义地址记录错误异常Observable_Exception::attach(new Logging_Exception_Observer('/tmp/test11.log'));Observable_Exception::attach(new Email_Exception_Observer());//自定义邮件接收人记录错误异常Observable_Exception::attach(new Email_Exception_Observer('123456@qq.com'));class MyException extends Observable_Exception{ public function test(){ echo 'this is a test!'; } public function test1(){ echo '我是 自定义的方法处理这个异常!'; }}try { throw new MyException("出现异常了,记录一下下!");} catch (MyException $e) { echo $e->getMessage(); echo '<hr/>'; $e->test(); echo '<hr/>'; $e->test1();}
4. カスタム例外処理クラス
ini_set('display_errors','off');function exceptionHandler_1($e){ echo '自定义异常处理器1'.__FUNCTION__; echo '异常信息:'.$e->getMessage();}function exceptionHandler_2($e){ echo '自定义异常处理器2'.__FUNCTION__; echo '异常信息:'.$e->getMessage();}set_exception_handler('exceptionHandler_1');set_exception_handler('exceptionHandler_2');//恢复到上一次定义过的异常处理函数restore_exception_handler();throw new Exception('测试');echo 'continue........';echo '<hr/>';
7. PHP エラーを処理する方法例外のような?
1. ErrorException を通じて
/** * 自定义错误异常类 */class ExceptionHandler{ protected $_exception; protected $_logFile='./testExceptionHandler.log'; function __construct(Exception $e){ //保存异常对象 $this->_exception = $e; } public static function handle(Exception $e){ $self = new self($e); $self->log(); echo $self; } public function log(){ $msg=<<<EOF 出现了通知错误,如下 产生通知的文件:{$this->_exception->getFile()}<br> 产生通知的信息:{$this->_exception->getTraceAsString()} 产生通知的行号:{$this->_exception->getLine()} 产生通知的错误号:{$this->_exception->getCode()} 产生通知的时间:{$datetime} \n EOF; echo $msg; error_log($msg, 3, $this->_logFile); } public function __toString(){ $message = <<<EOF <!DOCTYPE html> <html> <head> <title></title> </head> <body> <h1>出现异常了。。。。。</h1> <p>刷新下试试</p> </body> </html> EOF; return $message; }}ini_set('display_errors','off');set_exception_handler(array('ExceptionHandler', 'handle'));//放在try catch中的throwtry { throw new Exception("this is a test!",20010);} catch (Exception $e) { echo $e->getMessage();}//没放在try catch中的throwthrow new Exception("测试未捕获的自定义的异常处理器hello world!",2008);
2. カスタム例外クラス
function exception_error_handler($errno, $errstr, $errfile, $errline){ throw new ErrorException($errstr, 0, $errno, $errfile, $errline);}set_error_handler('exception_error_handler');try { echo gettype();} catch (Exception $e) { echo $e->getMessage();}
8. エラーが発生したときにユーザーを別のページにリダイレクトします
class ErrorToException extends Exception{ public static function handle($errno, $errstr) { throw new self($errstr, $errno); }}ini_set('display_errors', 'off');set_error_handler(array('ErrorToException', 'handle'));set_error_handler(array('ErrorToException', 'handle'),E_USER_WARNING|E_WARNING);try { echo $test; gettype(); trigger_error('test',E_USER_WARNING);} catch (Exception $e) { echo $e->getMessage();}
9. カスタム エラーと例外に渡す必要があるパラメーターを設定します。配信: $msg、$code
配信エラー: $errno、$errmsg、$errfile、$errline MyErrorHandler.php を参照
著作権表示: この記事はブロガーによるオリジナル記事であり、許可なく複製することはできませんブロガーの。

ホットAIツール

Undresser.AI Undress
リアルなヌード写真を作成する AI 搭載アプリ

AI Clothes Remover
写真から衣服を削除するオンライン AI ツール。

Undress AI Tool
脱衣画像を無料で

Clothoff.io
AI衣類リムーバー

AI Hentai Generator
AIヘンタイを無料で生成します。

人気の記事

ホットツール

メモ帳++7.3.1
使いやすく無料のコードエディター

SublimeText3 中国語版
中国語版、とても使いやすい

ゼンドスタジオ 13.0.1
強力な PHP 統合開発環境

ドリームウィーバー CS6
ビジュアル Web 開発ツール

SublimeText3 Mac版
神レベルのコード編集ソフト(SublimeText3)

ホットトピック











多くの場合、キーワードと追跡パラメーターで散らかった長いURLは、訪問者を阻止できます。 URL短縮スクリプトはソリューションを提供し、ソーシャルメディアやその他のプラットフォームに最適な簡潔なリンクを作成します。 これらのスクリプトは、個々のWebサイトにとって価値があります

2012年のFacebookによる有名な買収に続いて、Instagramはサードパーティの使用のために2セットのAPIを採用しました。これらはInstagramグラフAPIとInstagram Basic Display APIです。

Laravelは、直感的なフラッシュメソッドを使用して、一時的なセッションデータの処理を簡素化します。これは、アプリケーション内に簡単なメッセージ、アラート、または通知を表示するのに最適です。 データは、デフォルトで次の要求のためにのみ持続します。 $リクエスト -

これは、LaravelバックエンドとのReactアプリケーションの構築に関するシリーズの2番目と最終部分です。シリーズの最初の部分では、基本的な製品上場アプリケーションのためにLaravelを使用してRESTFUL APIを作成しました。このチュートリアルでは、開発者になります

Laravelは簡潔なHTTP応答シミュレーション構文を提供し、HTTP相互作用テストを簡素化します。このアプローチは、テストシミュレーションをより直感的にしながら、コード冗長性を大幅に削減します。 基本的な実装は、さまざまな応答タイプのショートカットを提供します。 Illuminate \ support \ facades \ httpを使用します。 http :: fake([[ 'google.com' => 'hello world'、 'github.com' => ['foo' => 'bar']、 'forge.laravel.com' =>

PHPクライアントURL(CURL)拡張機能は、開発者にとって強力なツールであり、リモートサーバーやREST APIとのシームレスな対話を可能にします。尊敬されるマルチプロトコルファイル転送ライブラリであるLibcurlを活用することにより、PHP Curlは効率的なexecuを促進します

顧客の最も差し迫った問題にリアルタイムでインスタントソリューションを提供したいですか? ライブチャットを使用すると、顧客とのリアルタイムな会話を行い、すぐに問題を解決できます。それはあなたがあなたのカスタムにより速いサービスを提供することを可能にします

2025 PHP Landscape Surveyは、現在のPHP開発動向を調査しています。 開発者や企業に洞察を提供することを目的とした、フレームワークの使用、展開方法、および課題を調査します。 この調査では、現代のPHP Versioの成長が予想されています
