我正在看可序列化DTO 上的文章C# - 数据传输对象。
文章包含这段代码:
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 ... 这不完全等同于不处理异常吗?
人机工程学:
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 {
// 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一样)。
不要这样做,
try
{
...
}
catch(Exception ex)
{
throw ex;
}
你会失去堆栈跟踪信息...
要么做,
try { ... }
catch { throw; }
要么
try { ... }
catch (Exception ex)
{
throw new Exception("My Custom Error Message", ex);
}
你可能想要重新抛出的原因之一是,如果你正在处理不同的例外,例如
try
{
...
}
catch(SQLException sex)
{
//Do Custom Logging
//Don't throw exception - swallow it here
}
catch(OtherException oex)
{
//Do something else
throw new WrappedException("Other Exception occured");
}
catch
{
System.Diagnostics.Debug.WriteLine("Eeep! an error, not to worry, will be handled higher up the call stack");
throw; //Chuck everything else back up the stack
}
第一; 在文章中的代码的方式是邪恶的。 throw ex会将异常中的调用堆栈重置为这个throw语句所在的位置; 失去了关于实际创建异常的信息。
其次,如果你只是像这样捕获并重新抛出,我没有看到任何附加价值,上面的代码示例将是一样的好(或者,如果没有尝试捕获,甚至更好)。
但是,有些情况下您可能想要捕捉并重新抛出异常。 记录可能是其中之一:
try
{
// code that may throw exceptions
}
catch(Exception ex)
{
// add error logging here
throw;
}