2012-01-12 66 views
2

谢谢大家的帮助。c#例外问题

当除数为1时,此代码不会生成我期望的内容.ExceptOne的基类不会被调用,但ExceptOne中的超链接不会显示。我错过了什么?!

控制台输出是:

输入除数
的WriteLine例外1 ...
的WriteLine例外2 ...
基ctor2
HTTP:// exc2.com
Writeline in finally

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

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

编辑

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

+0

谢谢,刚学这东西。然而,Writeline语句在该构造函数中得到执行... – steelponey 2012-01-12 09:49:50

+0

当然,在此之后您抛出异常......在构造函数中抛出异常不会阻止代码被执行(最多抛出),但它将阻止该对象被创建。 – 2012-01-12 09:51:37

+0

是的;尝试评论抛出新的Exception2(); ..你为什么写这个? – 2012-01-12 10:02:45

1

如果你看到,当你在构造提高ExceptOne例外,你把一个新的Exception2类型的异常这是不是在你的Main(...)方法时捕获的,因此它被抓住的一般例外子句。

0

发生这种情况是因为您在ExceptOne中引发了Exception2,导致Exception2被(System.Exception r)块的主方法捕获。

调用ExceptOne的基础,消息(由base(“base ctor 1”)设置)从不显示,因为该例外从未被捕获。