抛出异常
异常可以被运行时或者用户抛出
throw new ArgumentException();
C#7 抛异常
C#7之前,throw肯定是个语句。而现在它可以作为expression-bodied functions里的一个表达式:
public string Foo() => throw new NotImplementedException();
也可以写出三元条件表达式里:
string ProperCase(string value)=> value == null ? throw new ArgumentException("value"): value == ""?"": char.ToUpper(value[0])+value.Substring(1);
重新抛出异常
try{ .. }
catch(Exception ex)
{
//Log error 记录日志
...
throw; //重新抛出异常
}
如果使用throw ex代替throw的话,程序仍可运行,然是新传递的异常的Stacktrace属性就不会反应原始错误了。
使用C#6+,你可以这样简洁的重写上例
其它常见的情景是抛出一个更具体的异常类型:
try
{
..//Parse a DateTime from XML element data
}
catch(FormatException ex)
{
throw new xmlException("Invalid DateTime",ex);
}
注意:在组建XmlException的时候,我把原异常ex,作为第二个参数传了过去,这样有助于调试。
有时候你会抛出一个更抽象的异常,通常是因为要穿越信任边界,防止信息泄露。
System.Exception属性
StackTrace
它是一个字符串,展现了从异常发生地到catch块所有的被调用的方法。
Message
关于错误的描述信息
InnerException
引起外层异常的内层异常(如果存在的话)。而且InnerException本身还有可能含有InnerException
常见异常类型
TryXXX模式
public int Parse(string input);
public bool TyrParse(string input,out int returnValue);
如果解析失败,Pares方法会抛出异常,而TryPase方法会返回false。
public return-type XXX(input-type input)
{
return-type returnValue;
if(!TryXXX(input,out returnValue))
throw new YYYException(...)
return returnValue;
}