David Balažic
,
Ranch Hand
Dec 09, 2009 11:49:01
I have code like this:
How to not repeat the same catch code every time?
It would be easy with a C like preprocessor, but there is no such thing for Java ...
Use a common method which has the exception handling and pass the barX() method via reflection?
Regards,
David
John de Michele
,
Rancher
Dec 09, 2009 12:46:38
David:
Instead of having bar1() and bar2() methods, why not have a single bar() method, and just pass in a parameter?
John.
David Balažic
,
Ranch Hand
Dec 09, 2009 13:15:28
John de Michele wrote: David:
Instead of having bar1() and bar2() methods, why not have a single bar() method, and just pass in a parameter?
bar1 , bar2 are not my methods. I don't have control over them.
David Newton
,
Author
Dec 09, 2009 13:25:35
Extract the contents of the catch block. If it's a checked exception, if you call the method, you either need to catch it, or declare that the method throws it.
David Balažic
,
Ranch Hand
Dec 09, 2009 13:27:19
David Newton wrote: Extract the contents of the catch block.
Can you please tell more? Extract it to where?
David Newton
,
Author
Dec 09, 2009 13:42:04
To a new method? Extract Method is one of the most common refactorings.
David Balažic
,
Ranch Hand
Dec 09, 2009 13:51:19
I don't see how I could extract the catch code. Care to give an example?
Paul Clapham
,
Marshal
staff
Dec 09, 2009 14:02:58
David Balažic wrote: I don't see how I could extract the catch code. Care to give an example?
In Eclipse, select the code you want to make into a method and right-click on the selection. Somewhere in the options you will find Extract Method.
David Balažic
,
Ranch Hand
Dec 09, 2009 14:11:07
Of course.
First I was thinking about extracting the entire catch (and try)part which is impossible.
Extracting only the catch body is of course simple.
Still 3 lines that repeat, but better than nothing.
Thanks!
Ireneusz Kordal
,
Ranch Hand
Dec 09, 2009 15:30:44
You could do it using enums:
yeah, but ... what would PIE do? Especially concerning this tiny ad:
a bit of art, as a gift, the permaculture playing cards
https://gardener-gift.com