C# 中的异常为处理运行时发生的错误情况提供了一种结构化、统一且类型安全的方式。想要防止应用程序崩溃,妥善处理异常和错误就很重要。
在 C# 中,所有异常的基类型都是System.Exception类。它包含一些重要的属性,例如Message,其中含有供人阅读的说明,解释抛出该异常的原因。
如果要在代码的某个部分表明出现了错误,就需要创建一个新的异常对象,然后用throw关键字把它抛出:
using System;
static int Square(int number)
{
if (number >= 46341)
{
throw new ArgumentException($"Argument {number} cannot be higher than 46340 as its' square doesn't fit into int type.");
}
return number * number;
}
异常被抛出后,运行时会负责找到处理该异常的那段代码。如果找不到合适的处理程序,运行时除了停止程序的执行外,还会显示未处理异常的消息。
要为异常创建处理程序,C# 使用 try-catch 语句,它由一个try代码块和一个或多个catch子句组成。try代码块中应当包含并守护可能抛出异常的代码。catch子句则应当包含在错误发生后处理程序行为的代码。需要注意,try代码块之后各异常的顺序很重要:当列出多个异常时,会执行第一个匹配的catch子句。
try
{
if (number == 42)
{
throw new ArgumentException("The number cannot be equal to 42.", "number");
}
if (number < 0)
{
throw new ArgumentOutOfRangeException("number", "The number cannot be negative.");
}
// Process number ...
}
catch (ArgumentOutOfRangeException e)
{
Console.WriteLine($"Number is out of range: {e.Message}.");
}
catch (ArgumentException)
{
Console.WriteLine("Invalid number.");
}
在本练习中,你将为一个简单的整数计算器构建错误处理。为简化起见,已经提供了用于计算加法、乘法和除法的方法。
目标是让计算器能够正常工作,当传入实参16、51和+时,返回符合以下格式的字符串:16 + 51 = 67。
SimpleCalculator.Calculate(16, 51, "+"); // => returns "16 + 51 = 67"
SimpleCalculator.Calculate(32, 6, "*"); // => returns "32 * 6 = 192"
SimpleCalculator.Calculate(512, 4, "/"); // => returns "512 / 4 = 128"
本任务中要实现的主要方法是(static)SimpleCalculator.Calculate()方法。它接受三个实参。前两个实参是整数,将对它们进行运算。第三个实参是字符串类型,在本练习中需要实现以下运算:
+字符串进行加法运算*字符串进行乘法运算/字符串进行除法运算任何其他运算符号都应抛出ArgumentOutOfRangeException异常。如果运算实参是空字符串,那么该方法应抛出ArgumentException异常。当null作为运算实参传入时,该方法应抛出ArgumentNullException异常。
SimpleCalculator.Calculate(100, 10, "-"); // => throws ArgumentOutOfRangeException
SimpleCalculator.Calculate(8, 2, ""); // => throws ArgumentException
SimpleCalculator.Calculate(58, 6, null); // => throws ArgumentNullException
当尝试除以0时,计算器应返回内容为Division by zero is not allowed.的字符串。任何其他异常都不应由SimpleCalculator.Calculate()方法处理。
SimpleCalculator.Calculate(512, 0, "/"); // => returns "Division by zero is not allowed."