nested try blocks

eon

2[H]4U
Joined
Oct 11, 2003
Messages
2,218
So I have a while loop that where if an exception is thrown, I dont want to go to the main catch block, but stay within the while loop. Looks like this work but something doesnt feel like, as if this is bad practice or something. Is there a better way to do this?
Code:
try
{
	while(...)
	{
		try
		{

		}
		catch
		{

		}

	}


}
catch
{

}
 

calebb

[H]F Junkie
Joined
Mar 26, 2000
Messages
8,545
You're right in that if you don't want to exit the while loop when a particular exception occurs, then you must handle the exception inside the loop.

Depending on what you're doing, you might catch some different standard (or custom) exception inside the loop so you can handle it at execution time - the final catch(Exception ex) could be used for any exceptions you haven't anticipated and then re-throw.

You probably don't want to do something like Console.Write(ex.Message); inside a single catch(Exception ex) because if a truly unexpected exception occurred, you'd never know about it. This might leave your application in an unexpected state.

Better to

catch(WebException webex)
{
//maybe investigate the problem and decide if it's safe to continue or cleanup and throw ex;
}
catch(SqlException sqlex)
{
//investigate... etc
}
catch(Exception ex)
{
throw ex; //except don't do this as you lose your stack trace info. throw a new exception or just leave this catch off and let the outer try/catch handle it.
}

etc.


edit: interesting article on different design patterns in VB and C#:
 
Last edited:

FreiDOg

Supreme [H]ardness
Joined
Jul 7, 2001
Messages
4,456
The best advice for handling exceptions is always to handle what you can deal with and recover from where you can, and let the rest go.
There's nothing wrong of bad about nesting try blocks, in fact as some level you're almost always doing that because you very well may want to handle things like formatting, parsing or out of range conditions while not breaking out of the loop - things that will be specific to the current iteration of the loop, while letting more 'serious' errors go since they're unlikely to be able to recover from inside your loop.
 

Whatsisname

[H]F Junkie
Joined
Nov 15, 2000
Messages
10,202
I'd restructure it to get knocked out of the while loop, and be capable of restarting where it left off.

Constantly setting up and tearing down the try/catch block is going to be wicked slow.
 

calebb

[H]F Junkie
Joined
Mar 26, 2000
Messages
8,545
I'd restructure it to get knocked out of the while loop, and be capable of restarting where it left off.

Constantly setting up and tearing down the try/catch block is going to be wicked slow.

Performance is too situational to make a judgment call on whether or not the OPs application will be wicked slow.

For example, "setting up and tearing down" try/catch blocks on a book repricing application written in C# on a Pentium-3 1GHz system that performs 24,000,000 reprices per day against Amazon/Abe/Half/Alibris will use approximately 40ms per sec of processing time (roughly 4%) and (in my application) 30MB of memory. (each reprice has its own try/catch block).

I wouldn't call that "wicked slow." In fact, I'd call further optimization a "waste of expensive developer resources." (or academic)

On the other hand, if you were writing a 3D/FPS engine and you were "setting up and tearing down" 24,000,000 try/catch blocks per second, then there might be a problem.
 

PTNL

Supreme [H]ardness
Joined
Jan 2, 2005
Messages
4,196
Other than calebb's point about catching specific Exception types first, it's really situational on what you do with a caught exception. Some questions to ask yourself are:
- Why was an exception thrown?
- What is the root cause of the exception?
- Could this exception have been avoided with simple conditional checks?
- Are we able to inject or correct data with or without going back to the user?
- Should this exception (or the fact that an exception was even thrown) be bubbed up to the calling method?

All of these (and more) can affect how you handle exceptions.

Edit: As for the nesting of try-catch-finally, that also depends. Personally, if there's a lot going on in each of those try-catch blocks, I'd consider separating it to another method; especially if that inner block would be useful to have for other code blocks. Adding several try-catch blocks in a single method/function call could lead to an unwieldy "god" method that is difficult to enhance or troubleshoot. Oh, and "finally" blocks are your friend.
 
Last edited:

Whatsisname

[H]F Junkie
Joined
Nov 15, 2000
Messages
10,202
That is true, though to me, saving the state outside the while loop's block, allowing for restarting is such a simple restructuring it's likely to be worth it. Especially when dealing with libraries where throwing "exceptions" happens regularly.

If it was more complicated than that I'd definitely consider whether its worth the trouble or not.

Performance is too situational to make a judgment call on whether or not the OPs application will be wicked slow.

For example, "setting up and tearing down" try/catch blocks on a book repricing application written in C# on a Pentium-3 1GHz system that performs 24,000,000 reprices per day against Amazon/Abe/Half/Alibris will use approximately 40ms per sec of processing time (roughly 4%) and (in my application) 30MB of memory. (each reprice has its own try/catch block).

I wouldn't call that "wicked slow." In fact, I'd call further optimization a "waste of expensive developer resources." (or academic)

On the other hand, if you were writing a 3D/FPS engine and you were "setting up and tearing down" 24,000,000 try/catch blocks per second, then there might be a problem.
 

eon

2[H]4U
Joined
Oct 11, 2003
Messages
2,218
yes I already catch specific exceptions in the while loop where I ignore one exception, break out of the while loop on another, and just log all other exceptions. But thanks, I'll assume its ok to nest try/catch blocks.
 

KingKaeru

Supreme [H]ardness
Joined
Jul 16, 2000
Messages
6,466
Good points so far. without much context, another advice i can add is to limit one try block per function to increase legibility and thus maintainability and testability. A good rule of thumb is to keep try blocks at the outter most level of your functions.

Code:
function foo() {
  try
  {
	while(...)
	{
            doSomething();
	}
  }
  catch
  {

  }
}

function doSomething()
{ 
  try
  {
  }
  catch 
  {
  }
}
 
Top