【发布时间】:2016-05-06 13:29:29
【问题描述】:
我正在我的asp.net 4.5 web 应用程序中实现错误处理模块。
我创建了一个引发错误的 GUI,该 GUI 从特定 (Exception) 程序集的 list<Types> 或 Exception 类型中动态填充下拉选择器。
然后我想抛出选择的错误以测试如何捕获/处理它。
我可以部分工作,因为我可以根据类型抛出异常,但我必须将其转换为基本异常类型。实际的异常被“保留”为innerException,但我想尝试抛出特定的异常。
所以我的问题是:如何仅给定异常类型动态抛出异常?
protected void ddlExcep_SelectedIndexChanged(object sender, EventArgs e)
{
List<Type> ExTypes = GetExceptionList(); //list of SystemException.Exception (from assembly System.SystemException)
DropDownList Exceptions = (DropDownList)sender;
string exc = Exceptions.SelectedValue.Replace("System.","");
Type ExcType = (from E in ExTypes where E.Name == exc select E).FirstOrDefault();
throw (SystemException)Activator.CreateInstance(ExcType);
}
没有必要展示我是如何得出这个列表的,只是为了清楚起见 这是显示列表如何的代码:
public static T Instantiate<T>() where T : class
{
return System.Runtime.Serialization.FormatterServices.GetUninitializedObject(typeof(T)) as T;
}
public static List<Type> FindAllDerivedTypes<T>()
{
return FindAllDerivedTypes<T>(Assembly.GetAssembly(typeof(T)));
}
private List<Type> GetExceptionList()
{
List<Type> listExTypes = FindAllDerivedTypes<SystemException>();
return listExTypes;
}
【问题讨论】:
-
等一下,innerException 对于您显示的代码应该始终为空。看起来您已经在抛出您想要的类型的对象。你能进一步解释一下吗?
-
我正要输入相同的..以及为什么我们将其转换为 SystemException..?检查类型而不是字符串比较不是更好吗?
-
这段代码真的没有意义,你需要给我们更多的信息和你正在使用的实际代码。
-
@DavidG exTpes 是一个从基础 System.SystemException 派生的列表
-
啊,我明白了。异常被正确抛出,只是没有被您的代码捕获。所以框架在某个地方捕获了它并将其包装在另一个异常中。