为什么我们不使用一般异常类(例外)来捕获所有类型的例外[重复]

时间:2022-01-25 20:18:38

This question already has an answer here:

这个问题在这里已有答案:

Why do we use the more specific exceptions like IndexOutOfRangeException and DivideByZero exceptions when we can catch them in a catch block like this:

为什么我们可以使用更具体的异常,如IndexOutOfRangeException和DivideByZero异常,我们可以在这样的catch块中捕获它们:

try
{
    //Some Work
}
catch(Exception E){}

1 个解决方案

#1


3  

You should only ever write specific code to handle exceptions that you reasonably expect to be thrown. If you understand that specific code could throw a specific type of exception then you can determine exactly what to do in that situation. If you catch absolutely any type of exception then you will have no idea what the cause was and thus you can't know what should be done about it.

您应该只编写特定的代码来处理您合理期望抛出的异常。如果您了解特定代码可能会抛出特定类型的异常,那么您可以确定在该情况下要做什么。如果您完全捕获任何类型的异常,那么您将不知道原因是什么,因此您无法知道应该采取什么措施。

#1


3  

You should only ever write specific code to handle exceptions that you reasonably expect to be thrown. If you understand that specific code could throw a specific type of exception then you can determine exactly what to do in that situation. If you catch absolutely any type of exception then you will have no idea what the cause was and thus you can't know what should be done about it.

您应该只编写特定的代码来处理您合理期望抛出的异常。如果您了解特定代码可能会抛出特定类型的异常,那么您可以确定在该情况下要做什么。如果您完全捕获任何类型的异常,那么您将不知道原因是什么,因此您无法知道应该采取什么措施。