[英]Throwing exceptions in a PHP Try Catch block
我在Drupal 6 .module文件中有一個PHP函數。 我正在嘗試在執行更密集的任務(例如數據庫查詢)之前運行初始變量驗證。 在C#中,我曾經在我的Try塊的開頭實現了IF語句,如果驗證失敗則會拋出新的異常。 拋出的異常將在Catch塊中捕獲。 以下是我的PHP代碼:
function _modulename_getData($field, $table) {
try {
if (empty($field)) {
throw new Exception("The field is undefined.");
}
// rest of code here...
}
catch (Exception $e) {
throw $e->getMessage();
}
}
但是,當我嘗試運行代碼時,它告訴我對象只能在Catch塊中拋出。
提前致謝!
function _modulename_getData($field, $table) {
try {
if (empty($field)) {
throw new Exception("The field is undefined.");
}
// rest of code here...
}
catch (Exception $e) {
/*
Here you can either echo the exception message like:
echo $e->getMessage();
Or you can throw the Exception Object $e like:
throw $e;
*/
}
}
要重新做
throw $e;
不是消息。
只需從catch塊中刪除throw
- 將其更改為echo
或以其他方式處理錯誤。
它沒有告訴你只能在catch塊中拋出對象,它告訴你只能拋出對象 ,並且錯誤的位置在catch塊中 - 存在差異。
在catch塊中,你試圖拋出你剛抓到的東西 - 在這種情況下無論如何都沒有意義 - 而你試圖拋出的東西是一個字符串。
你正在做的事情的真實世界類比是接球,然后試圖在其他地方拋出制造商的標志。 您只能拋出整個對象,而不是對象的屬性。
throw $e->getMessage();
你試着扔一個string
作為旁注:例外通常是定義應用程序的異常狀態,而不是驗證后的錯誤消息。 當用戶為您提供無效數據時,也不例外
拋出需要一個由\\Exception
實例化的對象。 只有$e
catched可以發揮作用。
throw $e
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.