try-catch 块的用途是捕捉和处理工作代码所生成的异常。有些异常可以在 catch 块中处理,问题解决后异常不会再次引发;但更多情况下,唯一能做的是确保引发适当的异常。
示例
在此示例中,IndexOutOfRangeException 不是最适当的异常:ArgumentOutOfRangeException 对该方法更有意义。
C# | 复制代码 |
---|
class TestTryCatch
{
static int GetInt(int[] array, int index)
{
try
{
return array[index];
}
catch (System.IndexOutOfRangeException e) // CS0168
{
System.Console.WriteLine(e.Message);
throw new System.ArgumentOutOfRangeException("index", "Parameter is out of range.");
}
}
}
|
备注
产成异常的代码包括在 try 块中。在其后面紧接着添加一个 catch 语句,以便在 IndexOutOfRangeException
发生时对其进行处理。catch 块处理 IndexOutOfRangeException
,并引发更适当的 ArgumentOutOfRangeException
异常。
请参见