Hi,
Folks, forgive me, I'm pretty much a raw prawn when it comes to C#, and .NET generally... though I've been a professional programmer for 10 years.
I'm looking at this article: http://www.codeproject.com/KB/cs/datatransferobject.aspx on Serializable DTO's.
The article includes this piece of code:
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;
}
}
The rest of the article looks sane and reasonable (to a noob), but that try-catch-throw throws a WtfException... Isn't this exactly equivalent to not handling exceptions at all?
Ergo:
public static string SerializeDTO(DTO dto) {
XmlSerializer xmlSer = new XmlSerializer(dto.GetType());
StringWriter sWriter = new StringWriter();
xmlSer.Serialize(sWriter, dto);
return sWriter.ToString();
}
Or am I missing something fundamental about error handling in C#... It's pretty much the same as Java (minus checked exceptions), isn't it? ... i.e they both refined C++.
I did search: Both SO and google, and failed to find an "authorative answer" to exactly this question... though this thread seems to support my contention that try-catch-throw is-a no-op.
Cheers all. Thanx for your time.
EDIT:
Just to summarise for anyone who finds this thread in future...
DO NOT
try {
// do stuff that might throw an exception
} catch (Exception e) {
throw e; // this destroys the strack trace information!
}
The stack trace information can be crucial to identifying the root cause of the problem!
DO
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).
}
Catch the more specific exceptions before the less specific ones (just like Java).
Thank you all for your time.
Cheers all. Keith.
References: