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

百般思念 提交于 2019-11-30 13:11:12

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.

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