【问题标题】:How to dynamically throw Exception based on Type如何根据类型动态抛出异常
【发布时间】: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 派生的列表
  • 啊,我明白了。异常被正确抛出,只是没有被您的代码捕获。所以框架在某个地方捕获了它并将其包装在另一个异常中。

标签: c# asp.net exception


【解决方案1】:

好的,cmets 让我回顾并意识到转换为 SystemException 不是问题,而是我故意从我的页面中删除了 Page_Error 方法,从而导致代码继续运行到生成的下一行System.Web.HttpUnhandledException 一旦我添加了我的

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

抛出/捕获了正确的异常

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-04-11
    • 2023-04-09
    • 2021-06-28
    • 2015-12-17
    • 2018-11-26
    • 1970-01-01
    相关资源
    最近更新 更多