c# re-throw exception in a method designed to handle exceptions and preserve stacktrace -


i want write method handle exceptions , called inside catch block. depending on type of exception passed, exception either passed inner exception of new exception or re-thrown. how preserve stack trace in second case ?

example :

public void testmethod() {     try     {         // can throw exception specific project or .net exception          someworkmethod()      }     catch(exception ex)     {         handleexception(ex);     } }  private void handleexception(exception ex) {     if(ex specificexception)          throw ex; //will not preserve stack trace...     else          throw new specificexception(ex); } 

what not is, because pattern repeated in many places , there no factorization :

try {     someworkmethod(); } catch(exception ex) {     if(ex specificexception)          throw;     else          throw new specificexception(ex); } 

you need use throw without specifying exception preserve stack trace. can done inside catch block. can return handleexception without throwing original exception , use throw right afterwards:

public void testmethod() {     try     {         // can throw exception specific project or .net exception          someworkmethod()      }     catch(exception ex)     {         handleexception(ex);         throw;     } }  private void handleexception(exception ex) {     if(ex specificexception)          return;     else          throw new specificexception(ex); } 

as long use is categorize exception, preferred way 2 catch blocks:

public void testmethod() {     try     {         // can throw exception specific project or .net exception          someworkmethod()      }     catch (specificexception)     {         throw;     }     catch(exception ex)     {         throw new specificexception(ex);     } } 

with c# 6.0 can use when let exception fall through:

public void testmethod() {     try     {         // can throw exception specific project or .net exception          someworkmethod()      }     catch(exception ex) when (!(ex specificexception))     {         throw new specificexception(ex);     } } 

Comments

Popular posts from this blog

python - How to insert QWidgets in the middle of a Layout? -

python - serve multiple gunicorn django instances under nginx ubuntu -

module - Prestashop displayPaymentReturn hook url -