问题
I want to throw an exception at next catch, (I attached image)
Anybody know how to do this?
回答1:
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)
{
...
}
回答2:
C# 6.0
to the rescue!
try
{
}
catch (Exception ex) when (tried < 5)
{
}
回答3:
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 */
}
回答4:
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
.
来源:https://stackoverflow.com/questions/13573244/how-to-throw-exception-to-next-catch