本文包括以下代码:
public static string SerializeDTO(DTO dto) {
try {
XmlSerializer xmlSer = new XmlSerializer(dto.GetType());
StringWriter sWriter = new StringWriter();
xmlSer.Serialize(sWriter, dto);
return sWriter.ToString();
}
catch(Exception ex) {
throw ex;
}
}
本文的其余部分看起来很合理(对菜鸟而言),但是try-catch-throw引发了WtfException ... 这不完全等同于根本不处理异常吗?
Ergo:
public static string SerializeDTO(DTO dto) {
XmlSerializer xmlSer = new XmlSerializer(dto.GetType());
StringWriter sWriter = new StringWriter();
xmlSer.Serialize(sWriter, dto);
return sWriter.ToString();
}
还是我缺少有关C#中错误处理的基本知识?它与Java(减去检查的异常)几乎相同,不是吗?...也就是说,它们都精炼了C ++。
堆栈溢出问题重新抛出无参数的捕获和什么都不做之间的区别?似乎支持我的观点,即try-catch-throw是-no-op。
编辑:
总结一下,以便将来找到该线程的任何人...
不要
try {
// Do stuff that might throw an exception
}
catch (Exception e) {
throw e; // This destroys the strack trace information!
}
堆栈跟踪信息对于确定问题的根本原因可能至关重要!
做
try {
// Do stuff that might throw an exception
}
catch (SqlException e) {
// Log it
if (e.ErrorCode != NO_ROW_ERROR) { // filter out NoDataFound.
// Do special cleanup, like maybe closing the "dirty" database connection.
throw; // This preserves the stack trace
}
}
catch (IOException e) {
// Log it
throw;
}
catch (Exception e) {
// Log it
throw new DAOException("Excrement occurred", e); // wrapped & chained exceptions (just like java).
}
finally {
// Normal clean goes here (like closing open files).
}
在不太具体的异常之前捕获更具体的异常(就像Java)。
参考文献: