简体   繁体   English

是否应该在try catch中捕获异常类?

[英]Should the Exception Class always be caught in try catch?

Is it good coding practice to always catch the base Exception class in a try catch? 在try catch中始终捕获基本Exception类是不是很好的编码实践?

try
{
    //
    // Piece of code
    //
}
catch (CustomException $my_ex)
{
    // Handle CustomExcepton
}
catch (Exception $other_exceptions)
{
    // Handle all other exceptions
}

If so, why? 如果是这样,为什么?

In PHP you can install a global exception handler . 在PHP中,您可以安装全局异常处理程序 When needed you can catch exceptions in your code, all unhandled exceptions go to the global exception handler. 需要时,您可以捕获代码中的异常,所有未处理的异常都会转到全局异常处理程序。 Depending on your strategie, you decide what to do. 根据您的策略,您决定要做什么。

Of course, when you decide to die, a clear error message and a log is appreciated. 当然,当您决定死亡时,会发现明确的错误消息和日志。

In general, if you can recover from a exception, use a try .. catch block, otherwise let the global exception handler do his work, and do not recover. 通常,如果您可以从异常中恢复,请使用try .. catch块,否则让全局异常处理程序执行其工作,并且不进行恢复。

You should catch only exceptions you now how to handle. 你应该只捕获你现在如何处理的例外。 Others should bubble up to calling method and some global handler in the end. 其他人应该最终冒泡到调用方法和一些全局处理程序。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM