自定义异常C# [英] Custom Exception C#

查看:117
本文介绍了自定义异常C#的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想创建自己的自定义Exception(针对我自己的实践),我有Man类,并且我想检查名称(因此它不是空的,null的而且只有英文字符。
我是不知道我是否正确地执行了
1.我是否需要在Custom Exception类或Man's setter中编写处理错误(如果发生)的代码?
2。
3.欢迎对我的代码进行任何评论?改进。

I would like to create my own custom Exception (for my own practice), I have Man class and i would like to check the name (so its not empty, null and only English chars. I'm not sure if I'm doing this right, 1.do i need to write the code that handles with the error (if occures) in the Custom Exception class? or in the Man's setter? 2. Where should i use the "throw new Exception" for best practice? 3. any comments\improvements about my code would be welcome.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace prog
{
    class Program
    {
        static void Main(string[] args)
        {

            try
            {
                Man p = new Man("Dan");

            }
            catch (Exception e)
            {
                throw new NameNotValidException(e.Message);
            }


        }
}

class Man
{
    private string name;

    public string Name
    {
        get { return name; }
        set
        {
            if (name == "" || name == null)
            {
                throw new NameNotValidException("error");
            }

            name = value;
        }
    }

    public Man(string name)
    {
        this.name = name;
    }

}

class NameNotValidException : Exception
{
    public NameNotValidException()
    {
        Console.WriteLine("Please Write a valid name!");
    }

    public NameNotValidException(string message)
        : base(message)
    {
    }

    public NameNotValidException(string message, Exception inner)
        : base(message, inner)
    {
    }
}

谢谢!

推荐答案


  1. 在这种情况下,适合抛出 ArgumentNullException 代替。 您最终使用的哪个异常(您自己的或 ArgumentNullException )无关紧要,并且不会更改下面代码的结构或如何您应该处理异常。

  2. 您要检查,而不是名称

  3. 在调用代码处处理异常。如果调用代码不是为处理异常而设计的,则不要捕获该异常或使用 throw 重新抛出以保留堆栈跟踪。

  4. 在由于以下原因导致代码失败的位置抛出异常(在这种情况下,无效值

  5. 请谨慎使用getter / setter代码,您正在检查错误的值,还绕过了构造函数中的setter,在这种情况下,它永远不会引发异常。

  1. In this case it is more appropriate to throw ArgumentNullException instead. Which exception you end up using (your own or ArgumentNullException) does not matter and does not change the structure of the code below OR how you should handle an Exception.
  2. You want to check value, not name in the setter.
  3. Handle the exception at the calling code. If the calling code is not designed to handle the Exception then do not catch that Exception OR rethrow using throw to preserve the stack trace.
  4. Throw the exception at the location where the code fails due to... (invalid value in this case)
  5. Be careful with your getter/setter code, you were checking the wrong values and also bypassing the setter in the constructor in which case it would never throw an Exception to begin with.

您的Man类。

public class Man {
    public Man(string name)
    {
        // notice capital N for Name so it is set on the property, not the field
        // this will execute the setter for the Name property
        this.Name = name;
    }

    public Man(){} // optional, but do not include the parameterized constructor you had as it sets the private fields directly OR include additional validation

    private string name;
    public string Name
    {
        get { return name; }
        set
        {
            if (string.IsNullOrEmpty(value))
                throw new ArgumentNullException("Name cannot be null or empty");
            name = value;
        }
    }
}

处理异常的调用代码。

Calling code which handles the exception.

try
{
    // use parameterized constructor
    Man p = new Man("Dan"); 

    // or use an initializer
    Man p = new Man{Name = "Dan"}; 

    // the above initializer is actually short for
    Man p = new Man(); 
    p.Name = "Dan"; 
}
catch (ArgumentException e)
{
    Console.WriteLine("Error occurred!! Do something...");
}

这篇关于自定义异常C#的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆