Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/269.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 创建自己的异常并在C中使用它#_C#_Exception_Custom Exceptions - Fatal编程技术网

C# 创建自己的异常并在C中使用它#

C# 创建自己的异常并在C中使用它#,c#,exception,custom-exceptions,C#,Exception,Custom Exceptions,我试图理解如何以正确的方式使用自定义异常 我已经多次使用try/catch,但从未了解何时使用自己的类异常。我已经阅读并观看了很多教程,但我无法理解这一点 这是我的CustomException课程: [Serializable] class CustomException : FormatException { /// <summary> /// Just create the exception /// </s

我试图理解如何以正确的方式使用自定义异常

我已经多次使用try/catch,但从未了解何时使用自己的类异常。我已经阅读并观看了很多教程,但我无法理解这一点

这是我的
CustomException
课程:

[Serializable]
    class CustomException : FormatException
    {
        /// <summary>
        /// Just create the exception
        /// </summary>
        public CustomException()
        : base() {
        }
        /// <summary>
        /// Create the exception with description
        /// </summary>
        /// <param name="message">Exception description</param>
        public CustomException(String message)
        : base(message) {
        }
        /// <summary>
        /// Create the exception with description and inner cause
        /// </summary>
        /// <param name="message">Exception description</param>
        /// <param name="innerException">Exception inner cause</param>
        public CustomException(String message, Exception innerException)
        {
        }
    }
[可序列化]
类CustomException:FormatException
{
/// 
///只需创建例外
/// 
公共自定义例外()
:base(){
}
/// 
///创建带有描述的异常
/// 
///异常描述
公共自定义异常(字符串消息)
:base(消息){
}
/// 
///创建带有描述和内部原因的异常
/// 
///异常描述
///例外内因
公共CustomException(字符串消息,异常innerException)
{
}
}
这就是我尝试使用它的地方:

    /// <summary>
    /// Checks if parse works
    /// </summary>
    /// <returns></returns>
    public static int ParseInput(string inInt)
    {
        try
        {
            int input = int.Parse(inInt);
            return input;
        }
        catch (CustomException)
        {
            throw new CustomException();
        }
        catch (Exception ex)
        {
            MessageBox.Show("Use only numbers! " + ex.Message);
            return -1;
        }

    }
//
///检查分析是否有效
/// 
/// 
公共静态int-ParseInput(字符串inInt)
{
尝试
{
int input=int.Parse(inInt);
返回输入;
}
捕获(自定义异常)
{
抛出新的CustomException();
}
捕获(例外情况除外)
{
MessageBox.Show(“仅使用数字!”+ex.Message);
返回-1;
}
}

现在我做错了什么?因为程序崩溃在这一行
int input=int.Parse(inInt),它永远不会出现在我的自定义异常中?如果我真的使用了经典的
异常
类,那么一切都可以正常工作。

您定义的CustomException是一个比基本FormatException更具体的类(这就是继承的意义)。您无法用更具体的异常捕获更一般的异常。只有另一种方法。

在您的代码中,只有在您以前捕获到异常时才抛出您的异常类型,这是永远不会发生的,因为系统不会抛出它

通常你会这样做

try
{
    // do something 
    if (some condition) 
        throw new MyCustomException() ;
} 
catch (SomeOtherException e) 
{
    // Handle other exceptions 
} 
在您的情况下,系统将抛出一个
FormatException
,但不是您自己的异常类,因为它不知道它。由于异常类与
FormatException
更为具体,因此不会调用catch块。但是,它应该是这样工作的:

public static int ParseInput(string inInt)
{
    try
    {
        int input = int.Parse(inInt);
        return input;
    }
    catch (FormatException e)
    {
        throw new CustomException("Format error!", e);
    }
    catch (Exception ex)
    {
        MessageBox.Show("Use only numbers! " + ex.Message);
        return -1;
    }
}
此外,您的代码还有一个缺陷:当捕获到任何
异常时,将向用户显示一条消息,-1将是返回值(是否-1不是有效输入…?)。当捕获到
FormatException
时,错误处理将由调用方通过重新抛出异常来完成-为什么

请记住,例外情况不会“失败”:


发生这种情况是因为在您的案例中,
int.Parse(int)
引发了
FormatException
,并且对您的自定义异常一无所知(John\u Snow\u face.jpg)。 您可以使用
TryParse
方法:

int number;
bool result = Int32.TryParse(value, out number);
if(!result)
throw new CustomException("oops");

让我以一个问题开始我的答案:当代码中没有出现异常时,您认为如何捕获该异常

代码如下:

int input = int.Parse(inInt);
出现错误时抛出
FormatException
,但不抛出自己的
CustomException

您必须将其放入自己的代码中才能捕获它:

try
{
    …
    // the execution of this code needs to lead to throwing CustomException…
    throw new CustomException();
    …
}
// … for a handler of CustomException to make any sense whatsoever
catch (CustomException e)
{
    … handle here …
}

MSDN:
int.Parse
对您的自定义异常类型一无所知,因此它无法抛出异常。谢谢大家!!非常好,像往常一样!!:首先,您的awnser帮助我了解它是如何工作的,谢谢!第二mabey提出了一个愚蠢的问题,但在抛出捕获到异常后,程序停止。。我不知道如何使程序在异常之后继续…?您需要将对方法的调用放入
try catch
块中,当然,因为现在该方法将抛出异常。
try
{
    …
    // the execution of this code needs to lead to throwing CustomException…
    throw new CustomException();
    …
}
// … for a handler of CustomException to make any sense whatsoever
catch (CustomException e)
{
    … handle here …
}