如何基于类型动态引发异常

本文关键字:异常 动态 何基于 类型 | 更新日期: 2023-09-27 18:32:31

我正在我的asp.net 4.5 Web 应用程序中实现一个错误处理模块。

我创建了一个抛出 GUI 的错误,该 GUI 从特定(Exception)程序集的Exception类型list<Types>中动态填充下拉选择器。

然后,我想抛出选定的错误以测试它将如何捕获/处理。

我有这个部分工作,因为我能够根据类型抛出异常,但我必须将其转换为基本异常类型。实际的异常被"保留"为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;      
}

如何基于类型动态引发异常

好的,这些评论让我回头看,意识到SystemException的转换不是问题,而是我故意从我的页面中删除Page_Error方法,从而导致代码继续运行到下一行,System.Web.HttpUnhandledException一旦我添加了我的

 private void Page_Error(object sender, EventArgs e)
 {
    //handle code
 }

抛出/捕获了正确的异常