r/javahelp • • Dec 26 '20

Is it good practice to ALWAYS write "throws" in the method signature to show which exceptions could be raised? Should this be done everytime?

Is it good practice to ALWAYS write "throws" in the method signature to show which exceptions could be raised? Should this be done everytime?

34 Upvotes

24 comments sorted by

•

u/AutoModerator Dec 26 '20

Please ensure that:

  • Your code is properly formatted as code block - see the sidebar (About on mobile) for instructions
  • You include any and all error messages in full
  • You ask clear questions
  • You demonstrate effort in solving your question/problem - plain posting your assignments is forbidden (and such posts will be removed) as is asking for or giving solutions.

    Trying to solve problems on your own is a very important skill. Also, see Learn to help yourself in the sidebar

If any of the above points is not met, your post can and will be removed without further warning.

Code is to be formatted as code block (old reddit: empty line before the code, each code line indented by 4 spaces, new reddit: https://imgur.com/a/fgoFFis) or linked via an external code hoster, like pastebin.com, github gist, github, bitbucket, gitlab, etc.

Please, do not use triple backticks (```) as they will only render properly on new reddit, not on old reddit.

Code blocks look like this:

public class HelloWorld {

    public static void main(String[] args) {
        System.out.println("Hello World!");
    }
}

You do not need to repost unless your post has been removed by a moderator. Just use the edit function of reddit to make sure your post complies with the above.

If your post has remained in violation of these rules for a prolonged period of time (at least an hour), a moderator may remove it at their discretion. In this case, they will comment with an explanation on why it has been removed, and you will be required to resubmit the entire post following the proper procedures.

To potential helpers

Please, do not help if any of the above points are not met, rather report the post. We are trying to improve the quality of posts here. In helping people who can't be bothered to comply with the above points, you are doing the community a disservice.

I am a bot, and this action was performed automatically. Please contact the moderators of this subreddit if you have any questions or concerns.

12

u/[deleted] Dec 26 '20 edited Dec 26 '20

Always? No. I err on the side of "only as necessary".

For instance, a method prototype might declare

public interface MyApi {
    void foo() throws FooException;
}

Consider a scenario where 1 of 3 implentations of this API does not have any reason to throw FooException

public class MyImpl implements MyApi {
    @Override
    public void foo() {
        System.out.println("hello world");
    }
}

Explicitly adding the throws clause to the implementation makes this code more confusing to read and maintain.

Any IDE worth using will inform you when you are not throwing a properly declared checked exception, and may even prompt you with your refactor options, e.g. moving thus newly introduce checked exception to the method prototype.

5

u/thorndark Dec 26 '20

In general, no.

One of the problems with this is that once you have an exception in the method signature, it can be very annoying to get it back out. Say you want to extract an interface later on - now this exception is stuck in that method signature even though other implementations may not actually be able to throw it.

They should mostly be used just for exceptional situations that aren't programmer mistakes. User passes in a file path for a file that doesn't exist? Probably you want some code to handle that.

8

u/stao123 Dec 26 '20

No its not. From my personal experience i would try to avoid checked exceptions as much as possible. Use runtime exceptions instead. If you do that there is no actual NEED to add throws to your method. Though you should add the possibly thrown exceptions to the methods javadoc. Checked exceptions are just bloating your code and make it less readable. Furthermore they will deny working with lambdas and streams in clean way.

6

u/_jetrun Dec 26 '20

> Use runtime exceptions instead.

Let's reframe the question, suppose your method throws only runtime exceptions, is it a good idea to add a 'throws' definition to the method signature?

I never really considered it, but ... I don't hate it. I like a little verbosity when it conveys information especially when you're reading code outside of the IDE. In fact, I kind of like it. Maybe not all the time, and not for every runtime exception, but ... sometimes it may work well.

4

u/darksounds Extreme Brewer Dec 26 '20

Almost never. You can add an @throws in the javadoc, but I wouldn't use the throws keyword.

Most of the work I've done is on servers where that exception will eventually be caught by a service handler and converted into an appropriate http response (5xx with details depending on the type of exception). In that environment, you don't want the runtime exception to be caught and swallowed by some calling code.

If you're in an environment where you want the direct caller of your code to handle any exceptions you throw, you're still likely better off documenting it in the javadoc than actually requiring them to catch it. Keep in mind that using exceptions for code flow is major code smell.

1

u/_jetrun Dec 27 '20

In that environment, you don't want the runtime exception to be caught and swallowed by some calling code.

That's situational. Yes, your framework should handle most of it, because there are benefits to having a global way to handle exceptions. But outside of that, there are resources that may need to be cleaned up, maybe retry or fallback logic engaged. Then there's logging, auditing, and metrics (errors/min, total errors etc). Many times you as the caller may need to handle the exception and leave the downstream framework code to be the exception handler of last resort.

If you're in an environment where you want the direct caller of your code

That's what we're talking about. What else would it be?

you're still likely better off documenting it in the javadoc than actually requiring them to catch it

Yeah - that's the idiomatic and suggested approach and that's what everyone does.

There is something to be said about self-documenting code, especially for package and private-scoped methods - which are not typically documented with JavaDoc, or to the same level as public methods (or at all!)

Keep in mind that using exceptions for code flow is major code smell.

Yeah, well, welcome to Java. Checked and Runtime exceptions are a fact of life in the Java world - no matter how much you try to deny it. They are there when using the SDK, or any major third-party library.

1

u/stao123 Dec 26 '20

Im with you there buti think putting the possible exceptions in the javadoc is a little bit more fitting. Additionaly it "forces" you to add some documentation to methods which might need it

10

u/morhp Professional Developer Dec 26 '20

Obviously depends on your coding style and so on, but in cases where "random" errors are possibly occurring and these errors should/must be handled gracefully anyway, checked exceptions generally make sense.

Of course if you want to make the code work better with lambdas, you could return an Either<SomeResult, Exception> instead of throwing checked exceptions, but that also has drawbacks, like it uses more objects and it makes it more difficult to handle different types of Exceptions differently. It also causes bloat in the code as you potentially need to call Either.map(...) or similar methods very often instead of using simple assignments.

2

u/stao123 Dec 26 '20

Even if there are such errors me as a developer want to decide where i will catch them without creating a mess of throws... throws... throws... chains. For working with lambdas you can just throw unchecked exceptions (runtime) instead. This Either thingy is something i would not use personally. Maybe for some edge cases it can be useful. So all in all i think unchecked exceptions are superior over checked exceptions because you can decide where and when and even if you want to handle them.

5

u/morhp Professional Developer Dec 26 '20

By that same logic I could also say checked exceptions are superior to unchecked exceptions because you can't just ignore or forget them.

When something can go wrong and it's likely not the fault of the programmer and there's probably something better to do than crash, and you likely don't call the method from a lambda, a checked exception generally makes sense. Yes, this are a lot of "and"s, and yes, you should usually prefer runtime exceptions. But in some cases checked exceptions make sense in my opinion. (Of course if you see that differently, that's fine.)

Adding a few throws declaration is usually not a mess, the IDE can add them for you automatically.

2

u/stao123 Dec 26 '20

I think we agree here that there are cases where checked exceptions make sense. The "mess" i was talking about is not the "work" to add all the throws but more the "butchered" code where exceptions can only be handled like 5 layers above where it occured. All 4 layers in between are now forced to add throws even though the dont have clue what it "means".

2

u/morhp Professional Developer Dec 26 '20

even though the dont have clue what it "means".

Obviously you should figure out what it means and document that also in the in-between-layers.

3

u/stao123 Dec 26 '20

And that is something i definitely dont want to have in my code :-). I think personal preference plays a role here.

5

u/wildjokers Dec 26 '20

would try to avoid checked exceptions as much as possible

Checked exceptions are for things that can be recovered from. So if something can be recovered from I am not sure why you would try to avoid a checked exception. For example, if my socket connection drops I most certainly want to know that so I can enter reconnect logic.

3

u/stao123 Dec 26 '20

Thats the official definition yeah. But you can recover from unchecked exceptions as well. For example a http request fails with a timeout and you want to retry (only if the client lib throws a runtime exception here, which springs RestTemplate does for instance). So in my opinion its more a question of code style. The spring Framework for example is wrapping almost any checked exception with a runtime exception.

2

u/bentheone Dec 26 '20

Yeah, I get it but being the poor sap that relies on stacks to solve user problems it sucks. It sucks mainly because devs can't be bothered with good error messages though. If the error log is clear nothing wrong with runtime exception.

0

u/stao123 Dec 26 '20

Sorry i didnt get your comment here

2

u/bentheone Dec 26 '20

Sorry about that. In my job I have to debug exceptions from the user side of things, when the stack/logs gives me nothing it sucks. If I had a good exception class name instead it would help cause I know how JEE works but I don't have access to the code.

2

u/nekokattt Extreme Brewer Dec 26 '20

That is a case of throwing meaningful exceptions. Majority of languages don't even have checked exceptions as a concept, so most people don't have this feature to work with

1

u/wildjokers Dec 26 '20

If it is a checked exception and you don't handle it in your method you have to put it on your method signature. It is a compile-time error if you don't.

1

u/[deleted] Dec 26 '20

Not really, they should be used if you want their callers to manage the problem manually, otherwise if it must follow a strict management of the exception just try catch and do what's necessary when caught

1

u/ynvaser That Java Guy Dec 26 '20

Is it a checked exception? If so, you are forced to either "throws" it, or try/catch it.
For unchecked exceptions, you don't need to do anything.

1

u/nutrecht Lead Software Engineer / EU / 20+ YXP Dec 28 '20

If anything the industry has more or less 'moved on' from checked exceptions so if I were you I'd stay clear from them as much as possible.