• Post Reply Bookmark Topic Watch Topic
  • New Topic

Cleaning up try catch blocks  RSS feed

 
Greenhorn
Posts: 8
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi, I have the following code, where a call to a different method is made each time and the same exception is caught by each method. If the exception is thrown a call is made to the logError method with an int value defining the reason for the error. The logError method cannot be changed neither can the type of exception which each of the methods throw.

I have about 6 or 7 of these methods being called and feel there must be a more robust way of doing it, does anyone have any suggestions as to how it could be made neater.

 
Ranch Hand
Posts: 326
Android Firefox Browser Mac OS X
  • Likes 1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I can think of a number of ways to do this. If you have control over the code that throws the Exceptions, you could create your own custom Exceptions that contains the error constants so that you can just do e.getErrorCode().

If the method calls are consecutive in the calling method then you can consider the method to have a state and you just need to know where the call chain was when the error occurred. Like this:



I know that the code you provided is just example code but I would like to suggest to you to never catch anonymous Exception. Use the actual thrown Exception.
 
Alistair J MacDonald
Greenhorn
Posts: 8
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thanks for that, I did try a few different solutions but I think I was trying to overcomplicate a simple problem.

Yes the code provided is simply example code, the specific error is caught in the catch block.
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!