简体   繁体   中英

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?

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 eg 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.

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).

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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM