抛出异常

异常可以被运行时或者用户抛出

  1. throw new ArgumentException();

未命名图片.png

C#7 抛异常

C#7之前,throw肯定是个语句。而现在它可以作为expression-bodied functions里的一个表达式:

  1. public string Foo() => throw new NotImplementedException();

也可以写出三元条件表达式里:

  1. string ProperCase(string value)=> value == null ? throw new ArgumentException("value"): value == ""?"": char.ToUpper(value[0])+value.Substring(1);

重新抛出异常

  1. try{ .. }
  2. catch(Exception ex)
  3. {
  4. //Log error 记录日志
  5. ...
  6. throw; //重新抛出异常
  7. }

如果使用throw ex代替throw的话,程序仍可运行,然是新传递的异常的Stacktrace属性就不会反应原始错误了。
未命名图片.png
使用C#6+,你可以这样简洁的重写上例
未命名图片.png
其它常见的情景是抛出一个更具体的异常类型:

  1. try
  2. {
  3. ..//Parse a DateTime from XML element data
  4. }
  5. catch(FormatException ex)
  6. {
  7. throw new xmlException("Invalid DateTime",ex);
  8. }

注意:在组建XmlException的时候,我把原异常ex,作为第二个参数传了过去,这样有助于调试。
有时候你会抛出一个更抽象的异常,通常是因为要穿越信任边界,防止信息泄露。

System.Exception属性

StackTrace
它是一个字符串,展现了从异常发生地到catch块所有的被调用的方法。
Message
关于错误的描述信息
InnerException
引起外层异常的内层异常(如果存在的话)。而且InnerException本身还有可能含有InnerException

常见异常类型


未命名图片.png

TryXXX模式

  1. public int Parse(string input);
  2. public bool TyrParse(string input,out int returnValue);

如果解析失败,Pares方法会抛出异常,而TryPase方法会返回false。

  1. public return-type XXX(input-type input)
  2. {
  3. return-type returnValue;
  4. if(!TryXXX(input,out returnValue))
  5. throw new YYYException(...)
  6. return returnValue;
  7. }