• Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other Pie Elite all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Tim Cooke
  • Ron McLeod
  • Jeanne Boyarsky
  • Paul Clapham
Sheriffs:
  • Liutauras Vilda
  • Henry Wong
  • Devaka Cooray
Saloon Keepers:
  • Tim Moores
  • Stephan van Hulst
  • Tim Holloway
  • Al Hobbs
  • Carey Brown
Bartenders:
  • Piet Souris
  • Mikalai Zaikin
  • Himai Minh

Cleaning up try catch blocks

 
Greenhorn
Posts: 8
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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 Mac OS X Firefox Browser
  • Likes 1
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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
    Number of slices to send:
    Optional 'thank-you' note:
  • 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.
 
Consider Paul's rocket mass heater.
reply
    Bookmark Topic Watch Topic
  • New Topic