在C#中创建自己的exeception [英] Creating an own exeception in C#

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

问题描述

如何在C#中创建自己的例外?



示例假设我想要输入的年龄必须为正数,如果用户输入负值则必须抛出异常负数的例外。







以及C#中throw关键字的基本用法是什么?

解决方案

在您的方案中,我建议您使用 ArgumentOutOfRangeException [ ^ ](源自 ArgumentException [ ^ ]),当值为value时应该抛出一个论点是o取决于调用方法定义的允许值范围。


代码



 < span class =code-keyword> try  
{
int i = -1;
if (i < 0
{
throw new NegativeNumberException( 错误);
}
}
catch (NegativeNumberException nx)
{
MessageBox.Show(nx.Message) ;
}





用户定义的例外



  public   class  NegativeNumberException:System.Exception 
{
< span class =code-keyword> public NegativeNumberException()
{
}

public NegativeNumberException( string message)
base (message)
{
}

public NegativeNumberException( string message,System.Exception innerException)
base (message,innerException)
{
}
}


编写一个派生自Exception类的类,并在其中实现所需的逻辑



C#中的自定义异常.NET [ ^

How to create an own exception in C#?

example suppose i want entered age must be in positive number if user enter negative value then it must throw an exception of negative number exeption.



and also what is the basic use of throw keyword in C#?

解决方案

In your scenario I suggest you to use ArgumentOutOfRangeException[^] (derived from ArgumentException[^]), which should be thrown when the value of an argument is outside the allowable range of values as defined by the invoked method.


Code

try
            {
                int i = -1;
                if (i < 0)
                {
                    throw new NegativeNumberException("Error");
                }
            }
            catch (NegativeNumberException nx)
            {
                MessageBox.Show(nx.Message);
            }



User Defined Exception

public class NegativeNumberException : System.Exception
    {
        public NegativeNumberException()
        {
        }

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

        public NegativeNumberException(string message, System.Exception innerException)
            : base(message, innerException)
        {
        }
    }


Write a class derived from the Exception class and implement your required logic in it

Custom exceptions in C#.NET[^]


这篇关于在C#中创建自己的exeception的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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