[英]C# How to catch an exception on generic abstract class constructor
I am unable to catch an exception from a generic abstract class in the client app. 我无法从客户端应用程序中的通用抽象类中捕获异常。 The reason I want the exception to be thrown in the constructor is that the config file functionality needs to be the same in the derived classes and therefore I don't see a reason to implement this in every derived class. 我希望在构造函数中抛出异常的原因是配置文件功能在派生类中需要相同,因此我没有理由在每个派生类中实现它。 The exception should be handled in the overarching generic class AgentModule<T>
however, this is not the case for a reason I am unaware. 该异常应该在总体通用类AgentModule<T>
中处理,但是,由于我不知道的原因,情况并非如此。
I can catch the exception when I move the code to a method and invoke from the client class. 当我将代码移动到方法并从客户端类调用时,我可以捕获异常。
The abstract class: 抽象类:
public abstract class Importer
{
public abstract string Name { get; }
public abstract string Description { get; }
private System.Configuration.Configuration _customConfig;
public Importer()
{
string customConfigFile = this.GetType().Assembly.Location + ".config";
if (System.IO.File.Exists(customConfigFile))
{
System.Configuration.ExeConfigurationFileMap fileMap = new System.Configuration.ExeConfigurationFileMap();
fileMap.ExeConfigFilename = customConfigFile;
_customConfig = System.Configuration.ConfigurationManager.OpenMappedExeConfiguration(fileMap, System.Configuration.ConfigurationUserLevel.None);
}
else
{
throw new System.IO.FileNotFoundException("Could not load configuration file: " + customConfigFile);
}
}
public abstract void Load(ILogger logger);
}
The generic overarching class: 通用的总体类:
public class AgentModule<T> : ModuleBase where T : Importer, new()
{
private Importer _importer;
public override void Run()
{
try
{
_importer = (Importer)Activator.CreateInstance<T>();
}
catch (Exception e)
{
Console.WriteLine(e.Message);
}
}
}
Derived class: 派生类:
public class XLoad : Importer
{
public override string Name { get { return _name; } }
public override string Description { get { return _description; } }
private string _name;
private string _description;
public XLoad()
{
_name = "Load";
_description = "some desc";
}
public override void Load(ILogger logger)
{
Console.WriteLine("I am loading");
}
}
The Visual Studio debugger will not catch any exception for whatever happens within Activator.CreateInstance(). Visual Studio调试器不会捕获Activator.CreateInstance()中发生的任何异常。 But if you execute the exe manually/programmatically, this exception will be handled. 但是如果您手动/以编程方式执行exe,则将处理此异常。 You can even get the exception thrown at the constructor of the Importer class from the InnerException at AgentModule.Run() 您甚至可以从AgentModule.Run()的InnerException获取Importer类的构造函数抛出的异常。
try
{
_importer = (Importer)Activator.CreateInstance<T>();
}
catch (Exception e)
{
Console.WriteLine(e.Message);
if(e.InnerException != null)
Console.WriteLine(e.InnerException.Message );
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.