difference between throw and throw ex in c# .net [duplicate]

一世执手 提交于 2019-12-30 04:30:14

问题


Can anyone tell me difference between throw and throw ex in brief? I read that throw stores previous exceptions, not getting this line.
Can i get this in brief with example?


回答1:


Yes - throw re-throws the exception that was caught, and preserves the stack trace. throw ex throws the same exception, but resets the stack trace to that method.

Unless you want to reset the stack trace (i.e. to shield public callers from the internal workings of your library), throw is generally the better choice, since you can see where the exception originated.

I would also mention that a "pass-through" catch block:

try
{
   // do stuff
}
catch(Exception ex)
{
    throw;
}

is pointless. It's the exact same behavior as if there were no try/catch at all.




回答2:


Throw will rethrow original exception;

throw ex will create a new exception, so the stack trace changes. Usually makes little sense, in general you should either just throw, or create a new exception and throw that, eg

// not a great code, demo purposes only
try{
File.Read("blah");
}
catch(FileNotFoundException ex){
throw new ConfigFileNotFoundException("Oops", ex);
}


来源:https://stackoverflow.com/questions/21756461/difference-between-throw-and-throw-ex-in-c-sharp-net

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!