我有一個包含異常的類,如果異常未在類之外捕獲,我想要一個默認異常。覆蓋PHP中的默認異常消息
下面是一些代碼:
<?php
Class Test
{
public $file;
public function setFile($file)
{
$this->file = $file;
}
public function getFile()
{
return $this->file;
}
public function test()
{
try
{
return $this->getFile();
if($this->getFile() == "test")
{
throw new TestException("The variable is test!");
}
}
catch (TestException $e)
{
return "Default exception message: " . $e->getMessage();
}
}
}
class TestException extends \Exception
{
public function __construct($message)
{
parent::__construct($message);
}
}
$t = new Test;
$t->setFile('test');
try {
echo $t->test();
}
catch(TestException $e) {
//this wont do anything
return "I want to overwrite exception here... " . $e->getMessage();
}
此外,不使用與捕捉try塊將只是把一個未捕獲的異常錯誤。
那麼有沒有辦法來重寫處理?最明顯的方法是在類中拋出一個錯誤,刪除try塊,並在類外捕獲異常,但是我想知道是否有重寫的方法。