Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 626
lyates Avatar asked Jul 23 '09 01:07

lyates


4 Answers

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
like image 85
Thilo Avatar answered Oct 24 '22 00:10

Thilo


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

like image 20
Sam Harwell Avatar answered Oct 23 '22 23:10

Sam Harwell


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.

like image 40
Cowan Avatar answered Oct 24 '22 00:10

Cowan


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?

like image 33
JaredPar Avatar answered Oct 24 '22 00:10

JaredPar