PHP異常處理類BADMETHODCALLEXCEPTION使用方法

來源:互聯網
上載者:User


BadMethodCallException是PHP標準庫裡的異常處理類,是PHP內建的,比如在很多架構中可以看見繼承BadMethodCallException類,如Yii2中:


namespace yii\base;
 
/**
 * InvalidCallException represents an exception caused by calling a method in a wrong way.
 *
 * @author Qiang Xue <qiang.xue@gmail.com>
 * @since 2.0
 */
class InvalidCallException extends \BadMethodCallException
{
    /**
     * @return string the user-friendly name of this exception
     */
    public function getName()
    {
        return 'Invalid Call';
    }
}

BadMethodCallException類又是繼承BadFunctionCallException的:


 BadMethodCallException extends BadFunctionCallException {
/* 繼承的屬性 */
protected string $message ;
protected int $code ;
protected string $file ;
protected int $line ;
/* 繼承的方法 */
final public string Exception::getMessage ( void )
final public Exception Exception::getPrevious ( void )
final public int Exception::getCode ( void )
final public string Exception::getFile ( void )
final public int Exception::getLine ( void )
final public array Exception::getTrace ( void )
final public string Exception::getTraceAsString ( void )
public string Exception::__toString ( void )
final private void Exception::__clone ( void )
}

用法,在控制中:


public function actionResetPassword($token)
{
    try {
        $model = new ResetPasswordForm($token);
    } catch (InvalidParamException $e) {
        throw new BadRequestHttpException($e->getMessage());
    }
 
    if ($model->load(Yii::$app->request->post()) && $model->validate() && $model->resetPassword()) {
        Yii::$app->getSession()->setFlash('success', 'New password was saved.');
 
        return $this->goHome();
    }
 
    return $this->render('resetPassword', [
        'model' => $model,
    ]);
}

用於捕獲異常。

當然除了上面介紹的還異常處理類Exception


1、首先php5提供了基本的異常處理類,可直接使用
 
<?php
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(); // backtrace() 數組
final function getTraceAsString(); // 已格成化成字串的 getTrace() 資訊
/* 可重載的方法 */
function __toString(); // 可輸出的字串
}
?>

簡單的使用如下:(通過異常,拋出錯誤資訊)
 
try {
$error = 'my error!';
throw new Exception($error)
} catch (Exception $e) {
echo $e->getMessage();
}

2、我們可以擴充此類,方便我們的使用
 
class MyException extends Exception
{
// 重定義構造器使 message 變為必須被指定的屬性
public function __construct($message, $code = 0) {
// 自訂的代碼
// 確保所有變數都被正確賦值
parent::__construct($message, $code);
}
// 自訂字串輸出的樣式
public function __toString() {
return __CLASS__ . ": [{$this->code}]: {$this->message}\n";
}
public function customFunction() {
echo "A Custom function for this type of exception\n";
}
}

異常處理的基本思想是代碼在try代碼被調用執行。如果try碼塊出現錯誤,我們可以執行一個拋出異常的處理。某些程式設計語言,如java,,在特定情況下將自動拋出異常。在php中,異常必須手動拋出。可以使用如下方式拋出一個異常:
  Throw new Exception(‘message',code);
  Throw 關鍵字將觸發異常處理機制,它是一個語言結構,而不是一個函數,但是必須給它傳遞一個值。它要求一個接受對象。在最簡單的情況下,可以執行個體化一個內建的Exception類。
  最後,在try代碼之後,必須至少給出一個catch代碼塊。可以將多個catch代碼塊與一個try代碼塊進行關聯。如果每個catch代碼塊可以捕獲一個不同類型的異常,可以使用多個catch代碼塊是有意義的。例如,如果想捕獲Exception類的異常,代碼如下
 
Catch(Exception $e)
{
//handing exception
}
Catch代碼捕獲的對象就是導致異常並傳遞給throw語句的對象(被throw 語句拋出)。使用Exception 類的執行個體,是不錯的選擇。
Exception類提供了如下的內建方法:
  Getcode()   —返回傳遞給建構函式的代碼。
  GetMessage() —返回傳遞給建構函式的訊息。
  getFile()     —返回產生異常代碼的檔案的路徑
  getLine()    —返回產生異常的代碼所在的行。

注意:
當捕獲到一個異常後,try()塊裡面的後續代碼將不會繼續執行,而是會嘗試尋找匹配的“catch”代碼塊
當拋出一個異常後,如果不進行catch處理,則會報“Uncaught exception 'Exception'”錯誤
 
<?php
function test($val){
if ($val>100){
throw new Exception("提示資訊:您輸入的值過大");
}
}
test(111);
?>

3.當一個異常拋出後,catch語句塊可以進行處理也可以不處理
以下是我使用者註冊功能的部分代碼
 
try{
//check forms filled in
if(!filled_out($_POST)){
throw new Exception('你還沒有填寫表單,請回去填寫');
}
//check email address not valid
if(!check_email($email)){
throw new Exception('郵件的格式不正確');
}
//檢查密度的長度是否大於6
if(strlen($passwd<6)){
throw new Exception('密度的長度應該大於6');
}
//檢查兩次密碼是否相等
if($passwd!=$passwd1){
throw new Exception('兩次密碼不一樣,請重新輸入');
}
//檢查使用者名稱的長度是否正確
if(strlen($username)>16){
throw new Exception('使用者名稱的長度不符,請重新輸入');
}
} catch(Exception $e){
echo $e->getMessage(); //輸出異常資訊。
}

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.