C# try catch finally
C# try catch finally
try 语句指定受错误处理或清除代码影响的代码块。
try 块必须后跟 catch 块, finally 块,或两者。
当try块中发生错误时, catch 块执行。
执行 finally 块执行后离开 try 块执行清理代码,无论是否发生错误。
catch块可以访问包含有关的信息的 Exception 对象错误。
您使用catch块来补偿错误或重新抛出异常。
如果您只想记录问题,或者想要重新创建一个新的更高级别的异常类型,则重新抛出异常。
一个 finally 块会给你的程序添加确定性,CLR总是执行它。
它对清理任务(如关闭网络连接)很有用。
try语句如下所示:
try {
... // exception may get thrown within execution of this block
} catch (ExceptionA ex) {
... // handle exception of type ExceptionA
} catch (ExceptionB ex) {
... // handle exception of type ExceptionB
} finally {
... // cleanup code
}
例子
考虑下面的程序:
class Main {
static int Calc (int x) {
return 10 / x;
}
static void Main() {
int y = Calc (0);
Console.WriteLine (y);
}
}
为了防止运行时在x为0的情况下抛出DivideByZeroException,我们可以捕获异常,如下所示:
class Main {
static int Calc (int x) { return 10 / x; }
static void Main() {
try {
int y = Calc (0);
Console.WriteLine (y);
} catch (DivideByZeroException ex) {
Console.WriteLine ("x cannot be zero");
}
Console.WriteLine ("program completed");
}
}
catch子句
catch 子句指定要捕获的异常的类型。
这必须是 System.Exception 或 System.Exception 的子类。
捕获 System.Exception 捕获所有可能的错误。
您可以使用多个catch子句处理多个异常类型:
class Main {
static void Main (string[] args) {
try {
byte b = byte.Parse (args[0]);
Console.WriteLine (b);
} catch (IndexOutOfRangeException ex) {
Console.WriteLine ("Please provide at least one argument");
} catch (FormatException ex) {
Console.WriteLine ("That"s not a number!");
} catch (OverflowException ex) {
Console.WriteLine ("You"ve given me more than a byte!");
}
}
}
如果您不需要访问其属性,则可以捕获异常而不指定变量:
catch (StackOverflowException) // no variable
{
...
}
我们可以省略变量和类型,这意味着将捕获所有异常:
catch {
...
}
finally块
finally 块总是执行。
finally块通常用于清理代码。
static void methodA() {
StreamReader reader = null;
try {
reader = File.OpenText ("file.txt");
if (reader.EndOfStream) return;
Console.WriteLine (reader.ReadToEnd());
} finally {
if (reader != null) reader.Dispose();
}
}