【问题标题】:c# exception questionsc#异常问题
【发布时间】:2012-01-12 09:40:46
【问题描述】:

感谢大家的帮助。

当除数为 1 时,此代码不会产生我所期望的结果。未调用 exceptOne 的基类,未显示 exceptOne 中的超链接。我错过了什么?!

控制台输出是:

输入一个除数
1
WriteLine 异常 1...
WriteLine 异常 2...
基础 ctor2
http : // exc2.com
最后写一行

class Program
{
    static void Main(string[] args)
    {
        try
        {
            byte y = 0;
            byte x = 10;
            Console.WriteLine("enter a divisor");
            string s = (Console.ReadLine());
            y = Convert.ToByte(s);
            if (y == 1) throw new ExceptOne();
            Console.WriteLine("result is {0}", x / y); ;
        }

        catch (System.DivideByZeroException e)
        {
            Console.WriteLine("exception occured {0}...", e.Message);
        }

        catch (ExceptOne p)
        {
            Console.WriteLine(p.Message +"\n"+ p.HelpLink);

        }

        catch (System.Exception r)
        {
            Console.WriteLine(r.Message + "\n" + r.HelpLink);
        }

        finally
        {
            Console.WriteLine("Writeline in finally ");
            Console.ReadLine();
        }
    }
}

public class ExceptOne : System.Exception
{
    public ExceptOne()
        : base("base ctor 1 ")
    {
        this.HelpLink = "http://exc1.com";
        Console.WriteLine("WriteLine exception 1...");
        throw new Exception2();
    }
}

public class Exception2 : System.Exception
{
    public Exception2()
        : base("base ctor2 ")
    {
        Console.WriteLine("WriteLine exception 2...");
        this.HelpLink = "http://exc2.com";
    }
}

【问题讨论】:

    标签: c# exception custom-exceptions


    【解决方案1】:

    您在 exceptOne 异常的构造函数中抛出异常。因此永远不会创建一个异常对象,也不会触发该异常的捕获。

    编辑

    在构造函数中抛出异常是可以的。请参阅:http://bytes.com/topic/c-sharp/answers/518251-throwing-exception-constructorWhen is it right for a constructor to throw an exception?

    【讨论】:

    • 谢谢,刚刚学习了这些东西。但是,Writeline 语句确实在该构造函数中执行...
    • 当然,然后你抛出异常......在构造函数中抛出异常不会阻止代码被执行(直到抛出),但它会阻止对象被已创建。
    • 是的;尝试评论 throw new Exception2(); ..你为什么写这个?
    • 我想我也想问的问题是,在构造函数中抛出异常是个坏主意,应该避免这种情况吗?
    【解决方案2】:

    如果您看到当您在构造函数中引发 ExceptOne 异常时,您会抛出一个新的 Exception2 类型的异常,它不会在您的 Main(...) 方法中捕获,因此它会在一般异常子句中被捕获。

    【讨论】:

      【解决方案3】:

      发生这种情况是因为您在 exceptOne 中抛出 Exception2 导致 Exception2 在您的 main 方法中被 (System.Exception r) 块捕获。

      ExceptOne 的基础被调用,消息(由 base("base ctor 1 ") 设置)永远不会显示,因为该异常永远不会被捕获。

      【讨论】:

        猜你喜欢
        • 2011-01-18
        • 2011-04-27
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2014-10-19
        • 1970-01-01
        • 1970-01-01
        • 2022-12-06
        相关资源
        最近更新 更多