繁体   English   中英

C#异常问题

[英]c# exception questions

谢谢大家的帮助。

当除数为1时,此代码不会产生我期望的结果。不会调用ExceptOne的基类,也不会显示ExceptOne中的超链接。 我想念什么?

控制台输出为:

输入除数
1
WriteLine异常1 ...
WriteLine异常2 ...
基本ctor2
http:// exc2.com
最终进入Writeline

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";
    }
}

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

编辑

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

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

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

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM