Win a copy of Murach's Python Programming this week in the Jython/Python forum!
  • Post Reply Bookmark Topic Watch Topic
  • New Topic

Catching an exception in a thread  RSS feed

 
Tom Hughes
Ranch Hand
Posts: 86
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi,
I have the following code,

productController.loadProducts() throws IOException. I would like to catch these exceptions and make loadAllDataConcurrently throw them.
Is this possible ? Ideally I would declare run() to throw IOException but this is illeagal.
any help appreciated,
Tom
[ August 25, 2002: Message edited by: Tom Hughes ]
 
Ron Newman
Ranch Hand
Posts: 1056
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
You could extend Thread (let's call it MyThread), put an Exception field inside the MyThread object, and then look at that field after joining the MyThread. If the exception is non-null, throw it.
Your run() will need to catch Exception, and copy the exception into that field.
[ August 25, 2002: Message edited by: Ron Newman ]
 
Jim Yingst
Wanderer
Sheriff
Posts: 18671
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I agree with Ron's suggestion. Note that when you re-throw an exception though (particularly one originating from a different thread) you can get a very misleading stack trace. The stack trace information is created at the time the exception is first created with new; it contains no information about where the exception was re-thrown. When debugging a complex system you may need this information too. I recommend using the nested exception constructors available in JDK 1.4 to create a new exception which wraps the original, containing the original stack trace plus info on where it was rethrown.

Of course Exception may be replaced by IOException or some other exception type, as appropriate. It's entirely possible for the wrapping exception to have a different type than the original. If you're creating custom exception classes, be sure to create constructors like

These allow you to use exception nesting in your own classes.
 
Tom Hughes
Ranch Hand
Posts: 86
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thanks both of you - that really helped
Tom.
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!