我正在研究W3schools的例外情况Link,在标题之前的链接内:
“重新抛出异常”
有句话说:
“如果抛出的异常属于类CustomException并且存在 没有customException catch,只有基本异常catch,the 异常将在那里处理。“
如果有人可以给我一个这句话的例子,我将非常感激。
答案 0 :(得分:7)
基本上他们说如果你没有设置catch语句来捕获customException
它会落入一般Exception
catch语句。
在此示例中,第一个catch语句将捕获customException
,因为它明确地旨在实现此目的。
try {
// fail
throw new customException();
}
catch (customException $e) {
// catch custom exception
}
catch (Exception $e) {
// catch any uncaught exceptions
}
在下一个例子中,因为它缺少通用Exception
catch块的那个子句将会捕获它:
try {
// fail
throw new customException();
}
catch (Exception $e) {
// catch any uncaught exceptions
}
答案 1 :(得分:3)
在PHP手册的this page上查看示例#2
并且w3schools不是学习PHP的最佳地方,因其错误而闻名
答案 2 :(得分:2)
假设您将自定义异常定义为
class CustomException extends Exception
。
现在代码中的某处:
try
{
// do something that throws a CustomException
}
catch(Exception $e) // you are only catching Exception not CustomException,
// because there isn't a specific catch block for CustomException, and
// because Exception is a supertype of CustomException, the exception will
// still be caught here.
{
echo 'Message: ' .$e->getMessage();
}
所以它意味着因为CustomException是Exception的子类,只要你捕获超类的Exception类型而没有针对更具体的子类类型的catch块,它仍然会被捕获
答案 3 :(得分:2)
示例中有两个catch
块。第一个仅捕获customException
;下一个捕获任何Exception
。如果第一个块捕获任何东西,你永远不会到达第二个块。但由于customException
也是Exception
的示例,如果我们没有第一个catch
块,它就会被抓到。这样,第一个捕获捕获它,执行永远不会到达第二个。
与此同时,请阅读我上面发布的链接,以及为什么w3schools是一个坏主意。