Unnecessary Try Catch
From Software By Jeff
I have come upon another example of useless code. This is in my trip through some horrible JUnit tests. Here is some real code, with the important bits cut out or made to work so it will run.
public class UnnecessaryTest extends junit.framework.TestCase {
public void testUnnecessary() throws Exception {
try {
/* Anything you want */
} catch( Exception e ) {
throw e;
}
}
}
What is it about writing software that makes people do stupid things?
At first glance, it just looks like careful code. When just a little bit about JUnit is known, it fast becomes clear that the catching and throwing of the exception is pointless. Perhaps if something were done inside the catch block (which is why they exist), but except for cutting out anything in the try, this is the code of the tests. Yes, tests. This try/catch exists in every test in a dozen test classes, and in all of them, the only thing done in the catch block is to throw the exception.
That test should simply be written as thus:
public class UnnecessaryTest extends junit.framework.TestCase {
public void testBetter() throws Exception {
/* Anything you want */
}
}
Cut it out, people.
Also...found in PRODUCTION code
I'm sure someone was setting something up, but this is actual try/catch code I found while wandering through someone's code:
public class Foo {
public void foo() throws Exception {
try { } catch ( Exception e ) { /* Stuff here to log e */ }
}
}
Now, I know I truncate code examples and change the names, but in this case I only changed the contents of the catch block to comment the intent to log, while the real code had logger code in it. Otherwise, the contents of the try/catch are as in the real code.
Yes. That's right. Try NOTHING. Catch and log all Exceptions thrown by NOTHING.
Shoot me now.