C# 异常
2018-01-16 02:10 更新
C#异常
using语句
许多类封装了非托管资源。
这些类实现 System.IDisposable ,它定义了一个名为Dispose的单一无参数方法来清理这些资源。
using语句提供了一个优雅的语法,用于在finally块中的IDisposable对象上调用Dispose。
如下:
using (StreamReader reader = File.OpenText ("file.txt")) {
...
}
等效于:
StreamReader reader = File.OpenText ("file.txt");
try {
...
} finally {
if (reader != null) ((IDisposable)reader).Dispose();
}
抛出异常
异常可以由运行时或用户代码抛出。
在这个例子中,Display将抛出System.ArgumentNullException :
class Main {
static void Display (string name) {
if (name == null){
throw new ArgumentNullException ("name");
}
Console.WriteLine (name);
}
static void Main() {
try {
Display (null);
} catch (ArgumentNullException ex) {
Console.WriteLine ("Caught the exception");
}
}
}
重新抛出异常
您可以捕获并重新抛出异常,如下所示:
try {
...
} catch (Exception ex){
// Log error
...
throw; // Rethrow same exception
}
System.Exception的键属性
System.Exception的最重要的属性如下:
- StackTrace
一个字符串,表示从异常原点调用到catch块的所有方法。 - Message
错误的字符串描述。 - InnerException
引起外部异常的内部异常。
常见异常类型
以下异常类型广泛用于整个CLR和.NET Framework。
System.ArgumentException
抛出一个非法的赋值。
System.ArgumentNullException
当函数参数为null时抛出的ArgumentException的子类。System.ArgumentOutOfRangeException
当数值参数太大或太小时抛出的ArgumentOutOfRangeException的子类。
System.InvalidOperationException
当对象的状态不适合于方法时抛出。
System.NotSupportedException
引发支持的函数。System.NotImplementedException
抛出一个未实现的函数。System.ObjectDisposedException
当调用函数的对象已经布置时抛出。
TryXXX 方法模式
int类型定义两个其两个版本的Parse 方法:
public int Parse (string input); public bool TryParse (string input, out int returnValue);
如果解析失败, Parse 抛出异常; TryParse 返回 false 。
您可以通过 XXX 方法调用 TryXXX 方法来实现此模式,如下所示:
public return-type XXX (input-type input) {
return-type returnValue;
if (!TryXXX (input, out returnValue))
throw new YYYException (...)
return returnValue;
}
以上内容是否对您有帮助:

免费 AI IDE


更多建议: