我想知道使用InvalidArgumentException而不是Exception有什么好处? 这是为了增加代码的可读性还是有其他原因?
public function setShortName($shortName){
$shortName = (string) $shortName;
if (strlen( $shortName ) == 2) {
$this->_shortName = (string) $shortName;
} else {
throw new InvalidArgumentException( "Ülke kısa ismi 2 karakterden oluşmak zorundadır", 115003 );
}
}
或
public function setShortName($shortName){
$shortName = (string) $shortName;
if (strlen( $shortName ) == 2) {
$this->_shortName = (string) $shortName;
} else {
throw new Exception( "Ülke kısa ismi 2 karakterden oluşmak zorundadır", 115003 );
}
}
答案 0 :(得分:8)
这是为了更好的可读性/调试和处理正确的代码块,例如在try-catch块...
try {
// some code with potential exception throwing block
} catch(InvalidArgumentException $ex) {
// handling InvalidArgumentException
} catch(AnotherException $ex) {
// handling AnotherException
} catch(Exception $ex) {
// handling Exception
} finally {
// always-processed code
}
请注意,异常具有基于树的结构,因此处理取决于它们的顺序! (从最低到根)
了解更多信息:http://docs.oracle.com/javase/7/docs/api/java/lang/package-tree.html