Hướng dẫn lập trình .NET nêu rõ rằng chúng ta không nên nắm bắt các ngoại lệ chung. Tôi giả sử các mã sau đây không phải là rất tốt vì chung loại ngoại lệ bắt:.NET Catch Exceptions
private object CreateObject(string classname)
{
object obj = null;
if (!string.IsNullOrEmpty(classname))
{
try
{
System.Type oType = System.Type.GetTypeFromProgID(customClass);
obj = System.Activator.CreateInstance(oType);
}
catch (Exception ex)
{
Log.Error("Unable to create instance for COM Object with class name " + classname + "\n" + ex.Message);
}
}
return obj;
}
Trong đoạn mã sau tôi bắt ngoại lệ đặc biệt nhưng không phải tất cả trong số họ và sau đó tôi lại ném ngoại lệ trong trường hợp là khác nhau từ các ngoại lệ không chung chung. Tuy nhiên, chức năng "CreateInstance" có thể ném nhiều ngoại lệ (ArgumentNullException, ArgumentException, NotSupportedException, TargetInvocationException, MethodAccessException, MemberAccessException, InvalidComObjectException, MissingMethodException, COMException, TypeLoadException).
Có thể chấp nhận tất cả ngoại lệ cá nhân khác không? đây có phải là cách tốt hơn không?
private object CreateObject(string classname)
{
object obj = null;
if (!string.IsNullOrEmpty(classname))
{
try
{
System.Type oType = System.Type.GetTypeFromProgID(customClass);
obj = System.Activator.CreateInstance(oType);
}
catch (NotSupportedException ex)
{
Log.Error("...." + ex.Message);
}
catch (TargetInvocationException ex)
{
Log.Error("...." + ex.Message);
}
catch (COMException ex)
{
Log.Error("...." + ex.Message);
}
catch (TypeLoadException ex)
{
Log.Error("...." + ex.Message);
}
catch (InvalidComObjectException ex)
{
Log.Error("...." + ex.Message);
}
catch (Exception ex)
{
Log.Error("Unable to create instance for COM Object with class name " + classname + "\n" + ex.Message);
throw;
}
}
return obj;
}
Bản sao của: http://stackoverflow.com/questions/204814/is-there-any-valid-reason-to-ever-ignore-a-caught-exception –