Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why catch and rethrow an exception in C#?

I'm looking at the article C# - Data Transfer Object on serializable DTOs.

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? ... That is, they both refined C++.

The Stack Overflow question The difference between re-throwing parameter-less catch and not doing anything? seems to support my contention that try-catch-throw is-a no-op.


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).


References:

  • MSDN - Exception Handling
  • MSDN - try-catch (C# Reference)
like image 799
corlettk Avatar asked May 19 '09 07:05

corlettk


People also ask

Why do we need to Rethrow the exception in catch?

Sometimes we may need to rethrow an exception in Java. If a catch block cannot handle the particular exception it has caught, we can rethrow the exception. The rethrow expression causes the originally thrown object to be rethrown.

What does Rethrow the exception mean?

Re-throwing an exception means calling the throw statement without an exception object, inside a catch block. It can only be used inside a catch block.

Why do we catch exceptions?

You should catch the exception when you are in the method that knows what to do. For example, forget about how it actually works for the moment, let's say you are writing a library for opening and reading files. Here, the programmer knows what to do, so they catch the exception and handle it.

Is it good practice to Rethrow exception?

No of course not. There are cases when comment is still needed because the programming languages are not always best suited to describe what is going on very well.


2 Answers

First; the way that the code in the article does it is evil. throw ex will reset the call stack in the exception to the point where this throw statement is; losing the information about where the exception actually was created.

Second, if you just catch and re-throw like that, I see no added value, the code example above would be just as good (or, given the throw ex bit, even better) without the try-catch.

However, there are cases where you might want to catch and rethrow an exception. Logging could be one of them:

try  {     // code that may throw exceptions     } catch(Exception ex)  {     // add error logging here     throw; } 
like image 72
Fredrik Mörk Avatar answered Oct 13 '22 14:10

Fredrik Mörk


Don't do this,

try  { ... } catch(Exception ex) {    throw ex; } 

You'll lose the stack trace information...

Either do,

try { ... } catch { throw; } 

OR

try { ... } catch (Exception ex) {     throw new Exception("My Custom Error Message", ex); } 

One of the reason you might want to rethrow is if you're handling different exceptions, for e.g.

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 } 
like image 28
Eoin Campbell Avatar answered Oct 13 '22 13:10

Eoin Campbell