在c#中引发错误的语法是什么?

时间:2018-09-07 04:22:45

标签: c# exception error-handling

在python中,您可以执行以下操作

    def divide(numerator, denominator):
        if numerator == denominator:
            raise(ZeroDivisionError)

c#中的等价物是什么?

3 个答案:

答案 0 :(得分:3)

  

在C#中引发错误的语法是什么?

您通常询问的问题是Creating and Throwing Exceptions (C# Programming Guide)

节选:

  

异常用于指示在运行程序时发生了错误。创建描述错误的异常对象,然后使用throw关键字引发该对象。然后,运行时将搜索最兼容的异常处理程序。

class ProgramLog
{
  System.IO.FileStream logFile = null;
  void OpenLog(System.IO.FileInfo fileName, System.IO.FileMode mode) {}

  void WriteLog()
  {
    if (!this.logFile.CanWrite)
    {
      throw new System.InvalidOperationException("Logfile cannot be read-only");
    }
    // Else write data to the log and return.
  }
}

问题的实际答案是使用关键字throw

通常的用法是:

throw new Exception();
throw new ArgumentNullException();
throw new DivideByZeroException();

,如果您想rethrow the exception after you catch it

throw;

现在抛出异常时要考虑的东西很少; does the exception exist already,我应该考虑抛出什么异常。我建议您阅读Eric Lippert's Blog - Vexing exceptions,了解您应该考虑的接球和掷球方式。

答案 1 :(得分:0)

根据收到的评论进行更新-

这是您编写异常处理的方法,专门用于处理C#中的零偏移-

    static void Main(string[] args)
    {
        int number1 = 3000;
        int number2 = 0;
        try
        {
            divide(number1, number2);
        }
        catch (DivideByZeroException)
        {
            Console.WriteLine("Division error.");
        }

    }

    static void divide(int numerator, int denominator)
    {
        var devideResult = numerator / denominator;

    }

关于此的更多信息-

[https://docs.microsoft.com/en-us/dotnet/api/system.dividebyzeroexception?view=netframework-4.7.2][1]

---

时使用此异常
  

尝试分割一个对象时抛出的异常   整数或十进制值零。

答案 2 :(得分:-4)

public int Divide(int numerator, int denominator)
{
    try
    {
        return numerator / denominator;
    }
    catch (DivideByZeroException divideByZeroException)
    {
        Logger.Error("Divide by zero exception", divideByZeroException);
    }
    catch (Exception exception)
    {
        Logger.Error(exception);
    }

    return 0;
}