How to throw exception to next catch?
I want to throw an exception at next catch, (I attached image)
Anybody know how to do this?
You can’t, and trying to do so suggests that you’ve got too much logic in your catch
blocks, or that you should refactor your method to only do one thing. If you can’t redesign it, you’ll have to nest your try
blocks:
try { try { ... } catch (Advantage.Data.Provider.AdsException) { if (...) { throw; // Throws to the *containing* catch block } } } catch (Exception e) { ... }
C# 6.0
to the rescue!
try { } catch (Exception ex) when (tried < 5) { }
One possibility is nesting the try/catch clause:
try { try { /* ... */ } catch(Advantage.Data.Provider.AdsException ex) { /* specific handling */ throw; } } catch(Exception ex) { /* common handling */ }
there is also another way – using only your general catch statement and checking the exception type yourself:
try { /* ... */ } catch(Exception ex) { if(ex is Advantage.Data.Provider.AdsException) { /* specific handling */ } /* common handling */ }
This answer is inspired by Honza Brestan’s answer:
} catch (Exception e) { bool isAdsExc = e is Advantage.Data.Provider.AdsException; if (isAdsExc) { tried++; System.Threading.Thread.Sleep(1000); } if (tried > 5 || !isAdsExc) { txn.Rollback(); log.Error(" ... ... } } finally {
It’s ugly to have two try
blocks nested inside each other.
If you need to use properties of the AdsException
, use an as
cast instead of is
.