PHP Conference Japan 2024

DomainException 類別

(PHP 5 >= 5.1.0, PHP 7, PHP 8)

簡介

如果值不符合定義的有效資料域,則會擲出此例外。

類別概要

class DomainException extends LogicException {
/* 繼承的屬性 */
protected 字串 $message = "";
私有 字串 $string = "";
保護 整數 $code;
保護 字串 $file = "";
保護 整數 $line;
私有 陣列 $trace = [];
私有 ?Throwable $previous = null;
/* 繼承方法 */
公開 Exception::__construct(字串 $message = "", 整數 $code = 0, ?Throwable $previous = null)
最終 公開 Exception::getMessage(): 字串
最終 公開 Exception::getCode(): 整數
最終 公開 Exception::getFile(): 字串
最終 公開 Exception::getLine(): 整數
最終 公開 Exception::getTrace(): 陣列
}
新增註解

使用者貢獻的註解 4 則註解

mateusz dot charytoniuk at gmail dot com
13 年前
<?php
function renderImage($imageResource, $imageType)
{
switch (
$imageType) {
case
'jpg':
case
'jpeg':
header('Content-type: image/jpeg');
imagejpeg($imageResource);
break;
case
'png':
header('Content-type: image/png');
imagepng($imageResource);
break;
default:
throw new
DomainException('未知的圖片類型:' . $imageType);
break;
}
imagedestroy($imageResource);
}
?>
ja2016 at wir dot pl
7 年前
我認為這種例外很適合在預期的參數類型、值等正確,但其值超出定義域時拋出。看看 RangeException
>>在程式執行期間拋出以指示範圍錯誤的例外。通常這表示發生了除上溢/下溢以外的算術錯誤。這是 DomainException 的執行階段版本。<<
因此,這種例外是用於邏輯錯誤的。

當資料類型錯誤時,更好的方法是拋出 InvalidArgumentException。

<?php
// 這裡,使用 InvalidArgumentException
function media($x) {
switch (
$x) {
case
image:
return
'PNG';
break;
case
video:
return
'MP4';
break;
default:
throw new
InvalidArgumentException ("無效的媒體類型!");
}
}
?>
這與以下情況完全不同
<?php
// 這裡,使用 DomainException
$object = new Library ();
try {
$object->allocate($x);
} catch (
toFewMin $e) {
throw new
DomainException ("要分配的最小值太高").
}
?>
類似的情況,但問題發生在執行期間
<?php
class library {
function
allocate($x) {
if (
$x<1000)
throw new
RangeException ("Value is too low!")
}
}
?>
摘要:DomainException 與 RangeException 相似,我們應該在類似的情況下使用它們。但第一種例外設計用於我們確定問題出在我們的專案、第三方元素等時(簡而言之:邏輯錯誤),第二種例外設計用於我們確定問題出在輸入數據或環境時(簡而言之:執行階段錯誤)。
chmielewski dot thomas at gmail dot com
10 年前
<?php

function divide($divident, $divisor) {
if(!
is_numeric($divident) || !is_numeric($divisor)) {
throw new
InvalidArgumentException("函式僅接受數值");
}
if(
$divisor == 0) {
throw new
DomainException("除數不能為零");
}
return
$divident / $divisor;
}
Cruiser
6 年前
引言:「在資料管理和資料庫分析中,資料域是指資料元素可能包含的所有值。」

來源:https://en.wikipedia.org/wiki/Data_domain

這個例外讓我有點困惑,DataDomainException 或 DataTypeException 可能更具描述性。
To Top