只是想知道這是否是一種常見的做法。基本上這個構造函數正在調用一些導致失敗的初始化函數。我的想法是,將異常重新引回到創建對象的位置是有意義的,因爲這是實際輸出發送的地方。PHP從構造函數rethrow異常
這是這種情況的「最佳實踐」嗎?還是有更標準的方法來做到這一點?
<?php
class a {
private $x;
private $y;
function __construct($filename) {
try {
$this->x = $this->functionThatMightThrowException($filename);
$this->y = $this->doSomethingElseThatMightThrow();
}
catch(InvalidArgumentException $e) {
throw $e; //is this a good practice or not???
}
catch(Exception $e) {
throw $e; //again
}
}
//rest of class definition
}
// then somewhere else where the object is created and output is being sent
$fn = "blah.txt";
try {
$a = new a($fn);
}
catch (InvalidArgumentException $e) {
//actually handle here -- send error message back etc
}
catch (Exception $e) {
//etc
}
?>
如果你只是要重新拋出它,你爲什麼首先要抓住它? – PeeHaa
我會說這是多餘的。別擔心。讓他們通過未被捕獲的流行,不需要重新拋出它們。 – hakre
如果您沒有捕捉到特定的異常,它將簡單地執行備份執行鏈。捕捉並重新拋出相同的異常通常是毫無意義的。通常你只能抓到你實際想要處理的東西,然後讓其他人上樓去處理。這就像自助餐:如果你不想吃東西,那麼不要把它放在你的盤子上。 –