class ZeroDivisorException extends Exception{
public function __construct(){
parent::__construct('被0除異常', 101);
}
public function __toString(){
$msg = $this->getMessage();
$code = $this->getCode();
$file = $this->getFile();
$line = $this->getLine();
$ret = "/n-------------------------------------/n";
$ret .= "有錯誤發生!/n";
$ret .= "錯誤號碼: $code/n";
$ret .= "錯誤訊息: $msg /n";
$ret .= "檔案: $file/n";
$ret .= "行號: $line/n";
$ret .= "-------------------------------------/n/n";
return $ret;
}
}
class NotExactDivisionException extends Exception{
private $_integer;
private $_fraction;
public function __construct($integer, $fraction){
parent::__construct('不能整除異常', 102);
$this->_integer = $integer;
$this->_fraction = $fraction;
}
public function getInteger(){
return $this->_integer;
}
public function getFraction(){
return $this->_fraction;
}
}
function div($dividend, $divisor){
try{
echo "$dividend 除以$divisor -> /n";
if(0 == $divisor){
throw new ZeroDivisorException();
}
else if($dividend % $divisor != 0){
$integer = (int)($dividend / $divisor);
$fraction = $dividend % $divisor;
throw new NotExactDivisionException($integer, $fraction);
}
$result = $dividend / $divisor;
echo "結果為 $result/n/n";
}
catch(NotExactDivisionException $e){ #下面不能為"結果為:$e->getInteger(), 餘數為$e->getFraction()/n/n";
echo "結果為:".$e->getInteger().", 餘數為 ".$e->getFraction()."/n/n";
}
catch(ZeroDivisorException $e){
echo $e;
}
catch(Exception $e){ #通常應該把捕獲 Exception 類型異常的 catch 塊放在最後,以捕獲任何其它異常
echo $e;
}
}
div(100, 10);
div(100, 0);
div(100, 30);
?>