Throwable catching

Jonathan M Davis jmdavisProg at gmx.com
Sat Sep 28 01:50:59 PDT 2013


On Saturday, September 28, 2013 15:42:43 Alexandr Druzhinin wrote:
> catching Throwable is wrong. But is it wrong if I used it in separate
> thread to prevent thread dying like:
> 
> static void run()
> {
> 	while(true)
> 	{
> 		try
> 		{
> 			/// do work
> 			...
> 
> 			// interacting with parent
> 			auto msg = receiveTimeout(dur!"msecs"(1),
> 				(string command)
> 				{
> 					/// process command from parent
> 					if(some_condition_is_true)
> 						break; // finish
> 						       // execution
> 				}
> 			);
> 		}
> 		catch(Throwable t)
> 		{
> 			/// some diagnostic message
> 		}
> 	}
> }
> 
> ...
> 
> auto child = spawn(&run);
> 
> ...
> 
> ?

It's just as wrong to catch Throwable there is at is anywhere. If you do that 
you'll catch Errors, and Errors are _supposed_ to kill your program. They 
indicate that something bad enough has occurred that it's better to terminate 
your program than continue.

So, yes, what you're doing will keep the thread from dying, but if you get an 
Error, you want to shut your program down, not try and keep it running. So, 
maybe catching Throwable would make sense if you had to then tell the other 
thread to terminate, but should rethrow the Throwable afterwards and let the 
thread die.

- Jonathan M Davis


More information about the Digitalmars-d-learn mailing list