2

谢谢大家的帮助。

当除数为 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";
    }
}
4

3 回答 3

4

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

编辑

在构造函数中抛出异常是可以的。请参阅:http ://bytes.com/topic/c-sharp/answers/518251-throwing-exception-constructor以及构造函数何时抛出异常正确?

于 2012-01-12T09:45:26.983 回答
1

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

于 2012-01-12T09:50:58.717 回答
0

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

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

于 2012-01-12T09:51:32.493 回答