Le linee guida di programmazione .NET affermano che non dovremmo rilevare eccezioni generali. Suppongo che il seguente codice non è molto buona a causa del generale tipo di eccezione cattura:Eccezioni generali di catch .NET
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;
}
Nel codice seguente prendo particolari eccezioni, ma non tutti di loro e poi ri-generare l'eccezione nel caso in cui è diverso da le eccezioni non generiche. Tuttavia la funzione "CreateInstance" può generare molte eccezioni (ArgumentNullException, ArgumentException, NotSupportedException, TargetInvocationException, MethodAccessException, MemberAccessException, InvalidComObjectException, MissingMethodException, COMException, TypeLoadException).
È accettabile rilevare tutte le altre singole eccezioni? O c'è un modo migliore?
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;
}
Duplicato di: http://stackoverflow.com/questions/204814/is-there-any-valid-reason-to-ever-ignore-a-caught-exception –