PHP5的異常處理機制之使用Throw關鍵字_PHP教程

來源:互聯網
上載者:User
建立一個Exception對象後你可以將對象返回,但不應該這樣使用,更好的方法是用throw要害字來代替。throw用來拋出異常:

throw new Exception("my message", 44 );

  throw 將指令碼的執行中止,並使相關的Exception對象對客戶代碼可用。

  以下是改進過的getCommandObject() 方法:

  index_php5.php

 // PHP 5
 require_once('cmd_php5/Command.php');
 class CommandManager {
  private $cmdDir = "cmd_php5";

  function getCommandObject($cmd) {
   $path = "{$this->cmdDir}/{$cmd}.php";
   if (!file_exists($path)) {
    throw new Exception("Cannot find $path");
   }
   require_once $path;
   if (!class_exists($cmd)) {
   throw new Exception("class $cmd does not exist");
   }

   $class = new ReflectionClass($cmd);
   if (!$class->isSubclassOf(new ReflectionClass('Command'))) {
    throw new Exception("$cmd is not a Command");
   }
   return new $cmd();
  }
 }
?>

  代碼中我們使用了PHP5的反射(Reflection)API來判定所給的類是否是屬於Command 類型。在錯誤的路徑下執行本指令碼將會報出這樣的錯誤:

Fatal error: Uncaught exception 'Exception' with message 'Cannot find command/xrealcommand.php' in /home/xyz/BasicException.php:10
Stack trace:
#0 /home/xyz/BasicException.php(26):
CommandManager->getCommandObject('xrealcommand')
#1 {main}
thrown in /home/xyz/BasicException.php on line 10

  預設地,拋出異常導致一個fatal error。這意味著使用異常的類內建有安全機制。而僅僅使用一個錯誤標記,不能擁有這樣的功能。處理錯誤標記失敗只會你的指令碼使用錯誤的值來繼續執行。

http://www.bkjia.com/PHPjc/631402.htmlwww.bkjia.comtruehttp://www.bkjia.com/PHPjc/631402.htmlTechArticle建立一個Exception對象後你可以將對象返回,但不應該這樣使用,更好的方法是用throw要害字來代替。throw用來拋出異常: throw new Exception(my...

  • 聯繫我們

    該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

    如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

    A Free Trial That Lets You Build Big!

    Start building with 50+ products and up to 12 months usage for Elastic Compute Service

    • Sales Support

      1 on 1 presale consultation

    • After-Sales Support

      24/7 Technical Support 6 Free Tickets per Quarter Faster Response

    • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.