PHP教學-Try、Catch、Finally
PHP 快速導覽 - 例外處理 try catch throw
例外處理 (exception handling) 為控制程式發生錯誤後的機制, PHP 使用 try 、 throw 與 catch 三個關鍵字 (keyword) 進行例外處理。
PHP 5.5 以後增加 finally ,這是所有 catch 進行完一定會被執行的部份。
舉例如下
<?php
function inverse($x) {
if (!$x) {
throw new Exception('Division by zero.');
}
else return 1/$x;
}
try {
echo inverse(5) . "\n";
echo inverse(0) . "\n";
} catch (Exception $e) {
echo 'Caught exception: ', $e->getMessage(), "\n";
}
// Continue execution
echo "Hello World\n";
?>
以上範例會輸出:
0.2
Caught exception: Division by zero.
Hello World
錯誤發生的地方就用 throw 丟出例外物件 (object)
throw new Exception('Division by zero.');
有可能發生錯誤的地方就用 try 後面接大括弧圍起來,然後用 catch 捕捉例外物件,底下的大括弧為例外發生後處理的程式
try {
echo inverse(5) . "\n";
echo inverse(0) . "\n";
} catch (Exception $e) {
echo 'Caught exception: ', $e->getMessage(), "\n";
}
另一個例子增加 finally
<?php
function inverse($x) {
if (!$x) {
throw new Exception('Division by zero.');
}
return 1/$x;
}
try {
echo inverse(5) . "\n";
} catch (Exception $e) {
echo 'Caught exception: ', $e->getMessage(), "\n";
} finally {
echo "First finally.\n";
}
try {
echo inverse(0) . "\n";
} catch (Exception $e) {
echo 'Caught exception: ', $e->getMessage(), "\n";
} finally {
echo "Second finally.\n";
}
// Continue execution
echo "Hello World\n";
?>
以上範例會輸出:
0.2
First finally.
Caught exception: Division by zero.
Second finally.
Hello World
例外處理 (exception handling) 為控制程式發生錯誤後的機制, PHP 使用 try 、 throw 與 catch 三個關鍵字 (keyword) 進行例外處理。
PHP 5.5 以後增加 finally ,這是所有 catch 進行完一定會被執行的部份。
舉例如下
<?php
function inverse($x) {
if (!$x) {
throw new Exception('Division by zero.');
}
else return 1/$x;
}
try {
echo inverse(5) . "\n";
echo inverse(0) . "\n";
} catch (Exception $e) {
echo 'Caught exception: ', $e->getMessage(), "\n";
}
// Continue execution
echo "Hello World\n";
?>
以上範例會輸出:
0.2
Caught exception: Division by zero.
Hello World
錯誤發生的地方就用 throw 丟出例外物件 (object)
throw new Exception('Division by zero.');
有可能發生錯誤的地方就用 try 後面接大括弧圍起來,然後用 catch 捕捉例外物件,底下的大括弧為例外發生後處理的程式
try {
echo inverse(5) . "\n";
echo inverse(0) . "\n";
} catch (Exception $e) {
echo 'Caught exception: ', $e->getMessage(), "\n";
}
另一個例子增加 finally
<?php
function inverse($x) {
if (!$x) {
throw new Exception('Division by zero.');
}
return 1/$x;
}
try {
echo inverse(5) . "\n";
} catch (Exception $e) {
echo 'Caught exception: ', $e->getMessage(), "\n";
} finally {
echo "First finally.\n";
}
try {
echo inverse(0) . "\n";
} catch (Exception $e) {
echo 'Caught exception: ', $e->getMessage(), "\n";
} finally {
echo "Second finally.\n";
}
// Continue execution
echo "Hello World\n";
?>
以上範例會輸出:
0.2
First finally.
Caught exception: Division by zero.
Second finally.
Hello World
中英文術語對照 | |
---|---|
例外處理 | exception handling |
關鍵字 | keyword |
物件 | object |
不好意思,能否請教一下為何在inverse(0)的時候
回覆刪除if (!$x) {
throw new Exception('Division by zero.');
}
會輸出錯誤嗎?
不會錯誤
刪除因為0是false
!false > true
會傳入throw new Exception('Division by zero.');
所以
最後
Caught exception: Division by zero.
Second finally.