简体   繁体   English

我应该如何在C#中处理这个特殊异常?

[英]How should I handle this particular exception in C#?

I have a class called "Website", and inside of that class I have the following property: 我有一个名为“网站”的类,在该类中,我具有以下属性:

public HtmlForm RegisterForm
{
    get
    {
        if (Forms.RegForm != null) / Forms is a custom object called HTMLForms that is a custom list collection
        {
            return Forms.RegForm;
        }
        else
        {
            // FindPageWithGoogle Google = new FindPageWithGoogle();
            // use Google.FindRegistrationForm(this.currentUrl) method
            //throw new Exception(); // if registration form object can't be found
        }
        return Forms.RegForm;
    }
}

Would this be an efficient way of handling the error? 这是处理错误的有效方法吗? In the case of it not being found, how would I halt the entire flow of the program if this exception is thrown? 如果找不到该异常,如果引发此异常,我将如何停止程序的整个流程? I know how to use a simple try catch, but I don't think that's enough. 我知道如何使用简单的try catch,但是我认为这还不够。 I believe I need to learn how to make my own custom exception handling system to handle these custom events accordingly. 我相信我需要学习如何制作自己的自定义异常处理系统来相应地处理这些自定义事件。

Thanks for any help. 谢谢你的帮助。 Also, if you have a specific book on exception handling, since the C# books i've read thus far didn't go into the topic much, it would be greatly appreciated. 另外,如果您有一本关于异常处理的特定书籍,由于到目前为止我所阅读的C#书籍并未涉及太多主题,因此不胜感激。

Thanks, 谢谢,

Cody 科迪

To terminate the code on an exception, just don't catch it. 要终止异常代码,只需不要捕获它即可。

You should create a meaningful exception class (eg InitializationError ) and then throw that when the error occurs. 您应该创建一个有意义的异常类(例如InitializationError ),然后在发生错误时将其抛出。 Go out to the calling code that can display the message to the user and catch the exception there. 转到可以向用户显示消息的调用代码,并在那里捕获异常。 You might also terminate the program at that point. 您也可以在此时终止程序。

As far as books on exception handling, I think you'll find the MSDN chapter on exceptions helpful. 至于有关异常处理的书籍,我认为您会发现有关异常MSDN章节会有所帮助。

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

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