Php 抛出InvalidArgumentException而不是Exception有什么好处?
我想知道用InvalidArgumentException代替Exception有什么好处? 这是为了提高代码可读性,还是有其他原因Php 抛出InvalidArgumentException而不是Exception有什么好处?,php,exception,Php,Exception,我想知道用InvalidArgumentException代替Exception有什么好处? 这是为了提高代码可读性,还是有其他原因 public function setShortName($shortName){ $shortName = (string) $shortName; if (strlen( $shortName ) == 2) { $this->_shortName = (string) $shortName; } else {
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 );
}
}
或
它是为了更好的可读性/调试,以及处理正确的代码块,例如在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
}
请注意,异常具有基于树的结构,因此处理取决于它们的顺序!自下而上
有关详细信息:这是为了更好的可读性/调试以及处理正确的代码块,例如在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
}
请注意,异常具有基于树的结构,因此处理取决于它们的顺序!自下而上
有关更多信息:its用于更好的可读性/调试以及处理正确的代码分支,例如在try catch Block中,您可以使用多个catch块处理不同类型的异常。我同意您的看法,它将帮助我在catch Block中处理异常。its用于更好的可读性/调试和处理代码的右分支,例如在try-catch-block中,您可以使用多个catch块处理不同类型的异常。我同意您的观点,这将有助于我在catch块中处理异常。如果没有catch-InvalidArgumentException$ex块,catch-exception$ex是否会捕获InvalidArgumentException?是,因为Exception是InvalidArgumentException的父级,所以Exception是基于树的结构,Exception是根。如果没有catchInvalidArgumentException$ex块,catchException$ex会捕获InvalidArgumentException吗?是,因为Exception是InvalidArgumentException的父级,所以Exception是基于树的结构,Exception是根