Is there a particular naming convention for Java methods that throw exceptions?
Asked Answered
P

11

12

I'm tempted to add a suffix like "Ex" to differentiate methods (with similar signatures) that throw Exceptions from those that don't.

Is there such a convention?

Philoctetes answered 23/7, 2009 at 1:45 Comment(5)
Spring LDAP has 4 "authenticate" methods that don't throw exceptions. I'd like to add a new "authenticate" methods that *do^ throw exceptions and it would be preferable to name these new methods something that would differentiate them from those that don't.Philoctetes
There is a naming convention for the opposite, best-effort methods that ignore exceptions and carry on: methods called safeClose do not throw NullPointerExceptions, or IOException, or SQLException even when the close operation failed.Abscess
I need to catch the AuthenticationException from the "authenticate" methods so that I can deliver the reason for the failure to the user.Philoctetes
I am proud to announce that the Spring LDAP developers have implemented my request for delivering the AuthenticationException.Philoctetes
Very good question: there are cases when you are already in an Exception-handler, you prefer methods that don't throw more exceptions. e.g: commons.apache.org/proper/commons-io/javadocs/api-2.5/org/…Waikiki
C
21

Yes, you name them the same as methods that don't.

Isn't the exception specification enough?

Edit: If you have similar methods that throw/not throw, I recommend the Parse/TryParse pattern (Parse being replaced by the operation). .NET Framework uses it frequently (Dictionary<T,K>.TryGetValue, Monitor.TryEnter, int.TryParse, etc. etc.).

Edit: Coding Horror: TryParse and the Exception Tax

Colima answered 23/7, 2009 at 1:46 Comment(0)
A
18

Don't do that.

This is like asking "is there a naming convention for methods that take two Strings as parameters".

Java has checked exceptions, which means that you need to declare them anyway. So you can easily see if an exception will be thrown, and what type of exception. You cannot even compile code that calls the method without adding exception handling code.

Update: It seems your intention is to have methods that check if a certain condition is true, but you do not want to return just false, but throw an Exception if the condition is not met, so that you can also convey an explanation message (in the Exception). I think a prefix of "assert" or "ensure" makes sense:

 // instead of
 if (! isAuthenticated())
    throw new NotAuthenticatedException("not sure why at this point...");

 // you do
 assertAuthentication();
 // which will throw NotAuthenticatedException("proper explanation") inside
Abscess answered 23/7, 2009 at 1:47 Comment(0)
F
8

Why would you do such a thing in Java? It already has exception specifiers built into the language. The compiler will prevent you from calling a method which explicitly throws an exception without some action being taken on your part to handle or allow the exception to propagate?

Folger answered 23/7, 2009 at 1:46 Comment(0)
E
4

If you need these methods differentiated, I'm sure you can do it in the naming without using a suffix or anything, which is (as others have pointed out) pretty ghastly.

Why have:

boolean authenticate(String username, String password);

and (say)

void authenticateEx(String username, String password) throws WhateverException;

when you could actually make it a meaningful part of the name by conveying the actual intent:

void ensureCanAuthenticate(String username, String password);

// or

void assertValidCredentials(...);

// or

void authenticateOrDie(...);

... or any number of other (probably better) names which actually convey the intent rather than relying on a confusing suffix.

Eliza answered 23/7, 2009 at 10:50 Comment(0)
A
2

Exceptions are part of the method signature in Java, therefore such a naming convention would be redundant.

Anglofrench answered 23/7, 2009 at 1:47 Comment(0)
G
2

Hungarian notation for methods that throw exceptions? Quel horror!

Do you mean checked or unchecked exceptions? Why on earth would you want to do that?

When you think about it, you'd have to add your convention to every method, because there's always the potential of an error or NPE or some other thing that could go wrong.

The "throws" clause is enough when you have checked exceptions, and there's no good purpose on God's green earth for unchecked exceptions.

Don't do it. Please.

Glandulous answered 23/7, 2009 at 1:54 Comment(0)
E
2

Generally don't add it to method names.

Add throws instead.

int parseInt(String s, int radix) throws NumberFormatException

But personally i like for getter e.g.

    getFieldsOrThrow(java.lang.String key)
    getFieldsOrDefault(java.lang.String key, Value defaultValue)

https://developers.google.com/protocol-buffers/docs/reference/java/com/google/protobuf/Struct

Elfland answered 19/2, 2021 at 10:31 Comment(0)
R
1

There is no convention and adding an ex will make the name harder to read and ugly looking for the average java programmer.

But at sometimes I could imagine that it would make your code faster understandable to add a try to methods that are likely to throw an exception. Especially if they are unchecked.

It doesn't have to be something ugly like it could be found in many c/c++ programs where you use _name or mName for members or iValue for integers. But in java there are some conventions too. If a method will return an integer it is prefixed with is... set, get and test are the most used examples for this. All of this things are documented in the method header, through return type annotations etc... But adding one word to the function name makes it easier and faster to read and understand.

Why not use try to give programmers reading your code a subconscious hint that this method is likely to throw an exception. Like tryCopyFile instead of tryWriteFile.

Rectum answered 23/7, 2009 at 2:14 Comment(1)
I think the "try" prefix is not so good. To me, that seems to hint towards not throwing an exception. Like Lock.tryLock(), which will try to obtain a lock, but return false if that was not possible.Abscess
M
0

There is none that I'm aware of.

In my opinion, the only time something like that makes sense is in unit test cases (e.g., testFooExpectingException()). But that's not really what you're talking about.

Mechanistic answered 23/7, 2009 at 2:17 Comment(0)
M
0

There is no such convention because every method can throw exceptions, regardless of whether you declare them or not. It's also somewhat redundant in this day and age of IDE tooltips (unless you're not using an IDE of course).

I'm curious to know why you are tempted to use such a naming convention though.

Meghan answered 23/7, 2009 at 8:9 Comment(0)
V
0

Every once in a while you'll run into a case where it might make sense to have a method name like getSafely() (returns a default value in the case where the actual value is invalid, for code that doesn't care too much about real values vs placeholders) or its converse getOrBlowUp() (for fail-fast code where a missing value is technically possible but indicates a bug in the code that's supposed to set the value).

But the point here isn't "method 2 throws an exception, method 1 doesn't" -- because, as mentioned above, any code could throw a RuntimeException. The point is that the two methods have different error-handling semantics, specific to different use cases, and that's what the method names try to capture.

Even then, the code would usually be cleaner if you could just get away with one behavior or the other, and call the method get().

A useful parallel here might be the distinction between Systems Hungarian and Apps Hungarian in Hungarian Notation. (See also this piece on coding conventions from Joel on Software.)

  • Systems Hungarian just tells you the type of the variable, so integer count becomes iCount. This is the most common form of Hungarian notation and IMHO it's (1) pretty pointless with a modern IDE and (2) potentially deceptive, if someone changes the type declaration without renaming the variable.
  • Apps Hungarian tells you the purpose of the variable, so integer (or short, or ordinal ID object, or whatever, who cares?) index representing a data row becomes drIndex, and index representing an annotation column becomes acIndex. This is much more useful and much less likely to cause trouble.

Calling your method getEx() is Systems Hungarian.

Vallery answered 23/7, 2009 at 9:44 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.