HIT_girl
HIT_girl

Reputation: 875

Declaring 'throws Exception' when no code in a method would throw checked exception

I'm curious if there is harm or any undesired side effects in declaring throws Exception in a method that doesn't have any code that would throw a checked Exception. Specially talking in unit tests. A test may be declared like such

@Test
void testSomething() throws Exception {
    ... some test code but none that throw a checked exception ...
}

besides in IDE visualizing that code as unused, what are could be the issues with it ?

Upvotes: 2

Views: 76

Answers (4)

LowKeyEnergy
LowKeyEnergy

Reputation: 652

Your example is a unit test method, but the question applies to other methods as well.

Personally, I find this practice incredibly annoying when developing on a team, since anyone that wants to use that method must either catch the imaginary Exception when they call your method, or they have to become jerks themselves as they take the easy approach by throwing the imaginary Exception out of their own method... knowing that it's not a real threat and spreading the annoyance to others.

Upvotes: -1

fascynacja
fascynacja

Reputation: 2888

Possible scenario is, that while writing your test you might use code which throws checked exception:

getClass().getClassLoader().getResource(filePath).toURI();

The compiler will not warn you that you have to handle it, because your method signature has "throws Exception". So you might miss to handle the situation where uri syntax is not correct. This is very small issue though.

Upvotes: 0

Karol Dowbecki
Karol Dowbecki

Reputation: 44970

There is no harm doing this in a @Test method. In fact that's a handy test method template as with JUnit any unhandled, unexpected exception is a test failure which will be properly reported. By declaring throws Exception you don't have to use try-catch blocks when working with code that uses checked exceptions e.g. operations on filesystem that are part of your test setup but not test objective.

However you shouldn't be doing this in normal code as this forces whoever calls the method to handle Exception which makes no sense as it's not thrown.

Upvotes: 3

Thomas
Thomas

Reputation: 5094

The primary undesired side effect of arbitrarily adding code that you know doesn't do anything is that it's confusing to anyone who has to maintain it later(even you when you forget why you put it there in the first place).

Upvotes: 2

Related Questions