Should methods that throw RuntimeException indicate it in method signature? - java

For example, many methods in frameworks/JDK might throw
java.lang.SecurityException
but this is not indicated in the method signature (since that is a practice normally reserved for checked exceptions).
I want to argue that declaring RuntimeExceptions in method sigs has many benefits (akin to static type checking for example). Am I drunk or otherwise?

I would not declare an unchecked exception in the signature, since it is misleading to the user of that API. It is no longer obvious whether the exception has to be explicitly handled.
Declaring it in the javadoc is a better approach since it allows someone to handle it if they think it is necessary, but knowing they can ignore it if they want. This makes the separation between checked and unchecked clear.

From the Oracle Java tutorial:
"If it's so good to document a method's API, including the exceptions
it can throw, why not specify runtime exceptions too?" Runtime
exceptions represent problems that are the result of a programming
problem, and as such, the API client code cannot reasonably be
expected to recover from them or to handle them in any way. Such
problems include arithmetic exceptions, such as dividing by zero;
pointer exceptions, such as trying to access an object through a null
reference; and indexing exceptions, such as attempting to access an
array element through an index that is too large or too small.
Runtime exceptions can occur anywhere in a program, and in a typical
one they can be very numerous. Having to add runtime exceptions in
every method declaration would reduce a program's clarity.

Take a look at the javadoc for Collection#add
There's a whole slew of unchecked exceptions mentioned:
Throws:
UnsupportedOperationException - add is not supported by this collection.
ClassCastException - class of the specified element prevents it from being added to this collection.
NullPointerException - if the specified element is null and this collection does not support null elements.
IllegalArgumentException - some aspect of this element prevents it from being added to this collection.
If you have the patience, I'd recommend thoroughly documenting the possible exceptions thrown by your methods this way. In a way, it's even more important to do this for unchecked exceptions, as checked exceptions are somewhat self-documenting (the compiler forces the calling code to acknowledge them).

In my point of view it's better to declare runtime exceptions at least in the javadoc for the method. Declaring it in the signature makes it even more obvious what may happen when something goes wrong. This is my main reason for suggesting to provide this information.
FYI: as time has progressed (now in 2017) I am leaning now far more to documenting them in javadoc only and avoiding checked exceptions as much as possible.

In my view unchecked exceptions should never be declared in the method signature as that is contrary to their nature.
If, however, a method is likely to throw some unchecked exceptions noting the likely circumstances in #throws in Javadoc can be helpful for others invoking the method in understanding what can go wrong. This is only useful though for exceptions that the callers is likely to be able to handle (such as a NPE due to bad input etc.)

If you are writing an api for use by others, then there is ample reason for explicit documentation of your intent in the api and there is no downside to declaring RuntimeExceptions in the method signature.

This has to do with the discussion regarding checked exceptions. Most would agree that exceptions shouldn't be declared in methods signatures.
There is also a discussion regarding how runtime exceptions should be used. I agree with one poster that runtime exceptions should denote a programming error or a fatal condition. So there isn't much merit declaring them in the signature. Every method could potentially through one.

Related

Should I put throws IllegalArgumentException at the function?

I'm building a scientific software with lots of calculations and of course arguments can have wrong lengths etc... So I used IllegalArgumentException class as it seemed right name for the issue, but should I put the throws IllegalArgumentException at the function definition ?
I am asking this because after I wrote it, the Eclipse Editor didn't ask me to surround the function with try and catch. I thought this is how try and catch were enforced. I've read the Exception handling tutorial at Java.com yet I'm not sure I understood the part regarding my question right though.
RuntimeExceptions like IllegalArgumentException are used to indicate programming errors. The program itself should rarely be able to handle it. Someone needs to manually fix the code.
Potential RuntimeExceptions should be documented somehow in the function contract (i.e. javadoc), either with the explicit #throws, or while describing the inputs. If you don't have a javadoc for the function, you may want to add the throws clause just to document the potential pitfalls of using the function, but in general adding throws clauses for runtime exceptions is discouraged.
If giving a wrong length is not actually a programming error, but is an exception situation, I would create a new checked exception (such as BadLengthError). If it is not an exceptional situation, don't use exceptions for flow control.
There's two types of exceptions:
runtime exceptions (like IllegalArgumentException and NullPointerException for example) don't need to be explicitly caught, because they 'shouldn't happen'. When they do, of course, you need to handle them somewhere.
regular exceptions NEED to be caught or declared to be thrown because they represent a more intrinsically difficult kind of error.
You need to read up on Unchecked Exceptions - exceptions which inherit from RuntimeException. They don't need to be declared in the method header.
http://download.oracle.com/javase/tutorial/essential/exceptions/runtime.html
The last paragraph sums it up:
If a client can reasonably be expected
to recover from an exception, make it
a checked exception. If a client
cannot do anything to recover from the
exception, make it an unchecked
exception.
IllegalArgumentException (along with some others, for example NullPointerException) are examples of a RuntimeException. This type of exception is not what's known as a checked exception. Java requires that methods declare which checked exceptions they throw and that if a called method might throw a checked exception, the calling method should either declare that it throws the exception itself, or catch and handle it.
As such, my concrete recommendation would be no, don't declare it. Certainly, though, you don't want to be catching it. In most cases, you also don't want to be throwing it unless this is unexpected behaviour. If it's quite normal and reasonable for the the method to be getting a value it doesn't like, an Exception is the wrong way to handle it.
You might also want to consider making use of assertions.
the first point when understanding exceptions is that they are for exceptional situations. While thinking about your method you must ask: "Should this method throws an exception if an exceptional value is passed through?" If the answer is "yes", put it in your method declaration.
I don't know if you get the idea, but it's kind of simple. It's just a matter of practice.

Please explain RuntimeException in Java and where it should be used

I am following this great discussion at SO, titled: The case against checked exceptions , but I am unable to follow where exactly RuntimeException should be used and how it is different from normal Exceptions and its subclasses. Googling gave me a complex answer, that is, it should be used to deal with programming logic errors and should be thrown when no Exception should normally occur, such as in the default block of switch-case construct.
Can you please explain RuntimeException in greater detail here. Thanks.
I am unable to follow where exactly
RuntimeException should be used
That's probably because you are looking at an argument, i.e. people are disagreeing about exactly this point.
and
how it is different from normal
Exceptions and its subclasses.
Very simple: All subclasses of Exception (except for RuntimeException and its subclasses) are checked i.e. the compiler will reject the code unelss you catch or declare them in the method signature. However, subclasses of RuntimeException are unchecked.
Googling gave me a complex answer,
that is, it should be used to deal
with programming logic errors and
should be thrown when no Exception
should normally occur, such as in the
default block of switch-case
construct.
This is the conventional wisdom, which says that for everything that a program can usefully deal with, you should use checked exceptions because then the compiler will force you to deal with them. Conversely, programs can typically not deal usefully with programmer errors, thus they don't have to be checked. This is how the Java Standard API uses RuntimeException.
The discussion you linked to is sparked by the view of some people (this includes me) who think that checked exceptions lead to bad code and should therefore not be used. Since you can't disable exception checking in the compiler, the only way to do this is to use only RuntimeException and its subclasses.
One observation that IMO supports this view is that the conventional wisdom of "use unchecked exceptions only for programmer error" is in fact mainly a rationalization of backwards-reasoning: there is no code safety reason why the compiler should not force you to deal with programmer errors. However, something like NullPointerException and ArrayIndexOutOfBoundsException can crop up almost anywhere, and if those were checked, nobody would ever want to program in Java. Thus, the language designers had to make a, huh, exception for those, and make them unchecked. To explain this, they came up with the "unchecked exceptions are for programmer errors" story.
Quotes from Effective Java 2nd Edition, Item 58: Use checked exceptions for recoverable conditions and runtime exceptions for programming errors
The Java programming language provides three kinds of throwables: checked exceptions, runtime exceptions, and errors. There is some confusion among programmers as to when it is appropriate to use each kind of throwable. While the decision is not always clear-cut, there are some general rules that provide strong guidance.
The cardinal rule in deciding whether to use checked exception or an unchecked one is this:
Use checked exceptions for conditions from which the caller can reasonably be expected to recover. By throwing a checked exception, you force the caller to handle the exception in a catch clause or to propagate it outward. Each checked exception that a method is declared to throw is therefore a potent indication to the API user that associated condition is a possible outcome of invoking the method.
Use runtime exceptions to indicate programming errors. The great majority of runtime exceptions indicate precondition violations. A precondition violation is simply a failure by the client of an API to adhere to the contract specified by the API specification.
Here's an example:
When trying to read a file of arbitrary name, the file may not exists. It's not strictly a programming error when a file does not exist (e.g. perhaps it did before but was then accidentally deleted). Clients may want to recover from this. Thus, FileNotFoundException is a checked exception.
If you give a null string as a filename, then NullPointerException (or perhaps an IllegalArgumentException -- another contentious debate) should be thrown. Client of the API is supposed to provide a valid string value; null isn't. As far as the API is concerned, this is a programmer error, which was easily preventable. Both of these exceptions are runtime exceptions.
Item 59: Avoid unnecessary use of checked exceptions also provides additional guidance:
Checked exceptions are a wonderful feature of the Java programming language. Unlike return codes, they force the programmer to deal with exceptional conditions, greatly enhancing reliability. That said, overuse of checked exceptions can make an API far less pleasant to use. If a method throws one or more checked exceptions, the code that invokes the method must handle the exceptions in one or more catch blocks, or it must declare that it throws the exceptions and let them propagate outward. Either way, it places a nontrivial burden on the programmer.
The burden is justified if:
the exceptional condition cannot be prevented by proper use of the API, and
the programmer using the API can take some useful action once confronted with the exception.
Unless both of these conditions hold, an unchecked exception is more appropriate.
So here's a short summary of the recommendation from Effective Java 2nd Edition:
Preventable exceptions that happen due to API user errors should be unchecked.
Exceptions that can't be handled reasonably should also be unchecked.
Otherwise, the exception should be checked.
See also
Effective Java 2nd Edition
Item 58: Use checked exceptions for recoverable conditions and runtime exceptions for programming errors
Item 59: Avoid unnecessary use of checked exceptions
Item 60: Favor the use of standard exceptions
Item 61: Throw exceptions appropriate to the abstraction
Item 62: Document all exceptions thrown by each method
Technical definition
An unchecked exception is defined as RuntimeException and its subclasses, and Error and its subclasses. They do not have to be declared in a method's throws clause.
References
JLS 11.2 Compile-Time Checking of Exceptions
Related questions
In Java, when should I create a checked exception, and when should it be a runtime exception?
When to choose checked and unchecked exceptions
The case against checked exceptions
IllegalArgumentException or NullPointerException for a null parameter?

Curious: Why is the "throws <SomeSpecific>Exception" syntax required in Java alone?

We all know it is needed.
But WHY is it needed in Java alone, when other similar languages that have exception handling capablities don't require us to write "throws Exception"? Is there anyone who knows what was happening when Java language was designed and why they made it that way? Just curious.
P.S. This may not be a practical or really necessary question - it might not help me in anyway with my ongoing projects. But certain language features kindle my curiosity :D
Edit
Looks like my question was very vague! I think I worded the question wrongly. We need to use the "throws Exception" kind of syntax at some points during programming when dealing with Java code. But something like that is never needed in C# or C++ or even VB.Net and PHP. So why Java alone insists on this?
As other answers here have pointed out, the throws clause is only required for checked exceptions, which is a feature that currently only exists in Java.
The official answer as to why Java has checked exceptions is well documented:
Why did the designers decide to force
a method to specify all uncaught
checked exceptions that can be thrown
within its scope? Any Exception that
can be thrown by a method is part of
the method's public programming
interface. Those who call a method
must know about the exceptions that a
method can throw so that they can
decide what to do about them. These
exceptions are as much a part of that
method's programming interface as its
parameters and return value.
However, this decision is highly controversial, even within the Java community:
Recently, several well-regarded
experts, including Bruce Eckel and Rod
Johnson, have publicly stated that
while they initially agreed completely
with the orthodox position on checked
exceptions, they've concluded that
exclusive use of checked exceptions is
not as good an idea as it appeared at
first, and that checked exceptions
have become a significant source of
problems for many large projects.
Eckel takes a more extreme view,
suggesting that all exceptions should
be unchecked; Johnson's view is more
conservative, but still suggests that
the orthodox preference for checked
exceptions is excessive. (It's worth
noting that the architects of C#, who
almost certainly had plenty of
experience using Java technology,
chose to omit checked exceptions from
the language design, making all
exceptions unchecked exceptions. They
did, however, leave room for an
implementation of checked exceptions
at a later time.)
Personally, I find checked exceptions to be useful only when your API makes a habit of catching all exceptions and re-throwing them as something appropriate to your abstraction layer. For example, an in-memory object cache that happens to use a disk or SQL backend to cache data should never throw IOException or SQLException -- instead, it should throw (and declare) some user-defined exception like CacheFailureException or similar.
Also, you might find Ned Batchelder's article Exceptions in the Rainforest illuminating in regard to this question.
It declares that the method can raise an exception, and allows developers and their tools to ensure that they have considered that possibility.
However, the question is imprecise. The declaration is only required when the exception is a "checked" exception. And then, a more specific type of exception should be declared. Throwing a java.lang.Exception is poor style.
Runtime exceptions, that is, exceptions raised by the runtime when specific bugs are encountered, are not required to be declared. Runtime exceptions should be thrown when the error can be prevented by better programming, and doesn't depend on environmental conditions at runtime.
There are two types of exceptions
Checked Exceptions
UnChecked Exceptions
The throws clause tells which checked Exceptions are thrown by the method so that the caller can handle these in the code or they would have to add the throws clause so that in the end someone will have to handle these exceptions.
Java does not require you to write throws Exception on a function declaration, so it is not "needed" in general. It requires you to declare the exceptions that may be thrown by the function, which might be no exceptions at all, or just runtime exceptions. Indeed, using throws Exception is probably a sign of lazy coding, as it acts as an uninformative catch-all.
edit — well now that you've edited your question, the answer you're looking for (as others have said) is that Java has the concept of "checked" exceptions. It was simply a design decision, to supposedly improve code quality. It probably doesn't really help much in the long run; you can't fix a bad coder with a language trick.
Java is a very organized language which prevents in many situations the unexperient user from missing something relevant or of importance, at least so that errors can be displayed later with a good hint or explanation for what is missing. Forcing you to mention the exceptions on a function/method declaration is a way to keep with that politics and at the same time a way to allow you to define your own specific exceptions and putting them to use.
The point of declaring exceptions in Java was to force the programmer to handle the errors that can arise when executing the program. However, experience showed that in a lot of cases, programmers' "handling" of exceptions did not really handle the exceptions but instead ignored them:
void writeToFile() {
try {
...
} catch (IOException ex) {
// Nothing here
}
}
So in languages more recent than Java the designers preferred not to check exceptions, so that programs without error checking would at least crash with a meaningful stack trace, so you would have a bug easy to debug instead of your program "misteriously" malfunctioning.
Personally I like checked exceptions in Java because:
I do not mishandle exceptions.
Exceptions make me be aware of possible problems that my code could have.
Code is better documented that way.
but I can understand unchecked exceptions. Most of the time I handle an exception is to log it, wrap it with some subclass of RuntimeException and rethrow, because they could only be caused by bugs / misconfiguration / broken deployment. I like to use checked exceptions only for business rule violations.
As I have understood the rationale as put forward by the Java designers, the error situations are generally put in two categories:
Those that are non-fatal and the calling code with good reason should be able to recover from. FileNotFoundException when reading form files, and IOExceptions when working with sockets.
Those that are fatal if they cannot with good reason be expected by the calling code. This includes ArrayIndexOutOfBoundsException and ArithmeticException (when dividing by zero).

Why are Runtime Exceptions "unchecked" in Java?

Why does it make sense to have Runtime Exceptions UnChecked (as opposed to if they were Checked)?
If you didn't you would have to have try/catch blocks every time you accessed an array element, did a division operation and many other common scenarios.
To put it another way, imagine this code:
Map map = ...
int i = ...
(int[])map.get("foo")[3] = 2334 / i;
would have to check for ClassCastException, ArrayIndexOutofBoundsException, ArithmeticException, UnsupportedOperationException and NullPointerException just off the top of my head.
With Java the issue isn't unchecked exceptions. Checked exceptions are a highly controversial subject. Some say this was largely an experiment with Java and in practice they don't work but you will find plenty of people who argue they are good.
No one is arguing unchecked exceptions are bad however.
The idea of the two kinds of exceptions in Java (checked and unchecked) is that checked exceptions should be used for error conditions that can reasonably be expected to happen, and unchecked exceptions should be used for unexpected error conditions.
For example if a file isn't found, you get a FileNotFoundException, and it's reasonable to expect your program to be able to handle such a condition. Unchecked exceptions should be used only for problems that shouldn't happen, and that really mean that there is a bug in the program if such a problem happens. For example, a NullPointerException means that your program is trying to dereference a variable that is null and that's most likely a bug.
The Java compiler forces the programmer to handle checked exceptions. This makes the programming language safer - it means that the programmer is forced to think about error conditions, which should make the program more robust.
The compiler doesn't check unchecked exceptions, because unchecked exceptions aren't supposed to happen anyway and if they do, there's nothing that the program could reasonably do at runtime; the programmer must solve the bug.
There has been some criticism to this feature in Java, some people even call checked exceptions a failed experiment and some people propose to remove checked exceptions from Java.
This simply means that the compiler will not force you to look for an exception, but you can still throw it at runtime. As one benefit, this allows you to throw new exceptions from your classes without requiring you to alter your interface, causing callers to change their code.

Why have a project specific RuntimeException?

Is there any point in having a com.myco.myproj.MyProjRuntimeException,
which completley extends RuntimeException?
Yes. Do throw unchecked exceptions, and subclass them.
There is much talk about whether checked exceptions are really any good. In a nutshell, if I throw a checked exception, does my client really have anything to do with it?
Unchecked exceptions are a good way to notify your clients about exceptional situations (including illegal pre-conditions), and yet not burdening them with the need to wrap calls to your API with try-catch blocks, which most of the time basically serve no purpose, other than debugging, tracing, etc.
So why not throw a RuntimeException? It's not elegant, and it's less readable. Make it your own exception which derives from it, even if it's for no reason other than being more specific when throwing the exception.
It depends on if you want to handle the exceptional condition differently than other exceptions farther up the call stack. If you intend to catch and handle the exception, then I'd recommend creating the custom type. It makes for more legible code and cleaner catch clauses. If you're not going to catch the exception, then there's probably little reason to create a new type.
Not really. The extra information you get from having the exception name show up in a stack trace could be given by simply setting the message string of a standard RuntimeException. However (come to think of it), it might be useful to subclass RuntimeException simply to prepend a custom string onto any message.
I tend to only make custom checked exceptions; generally, the standard unchecked exceptions cover enough potential cases already.
Many people (me and the designers of C# included) believe that checked exceptions are a failed language experiment and avoid them. Then, creating your own exception hierarchy under RuntimeException is an obvious step.
in Effective Java, Joshua Bloch writes:
Use run-time exceptions to indicate
programming errors. The great majority
of run-time exceptions indicate
precondition violations.
That being said, you could use that run-time exception as a base class for a hierarchy of run-time exceptions, used in your project. That way, errors become more legible and traceable.
In my opinion, you should only create new Exceptions if you really need them, i.e. want to catch them and do a specific treatment on them. On all other cases, I don't really see the usefulness.
It's a good style to maintain your own exceptions hierarchy.
But I've seen just a few people who can use this technique with real profit.
Subclass exceptions based on how they are handled rather than who wrote them...
Normally runtime exception can't be handled in another way than logging the error and possibly display an error message.
Checked exceptions might possibly have a specific fallback, and in that case they should probly not subclass a "MyFrameWorkException" - as in that case, catching a MyFrameWorkException would not do more than the generic catch (logging etc.)
It is a rather bad practice to invent a whole hiearachy of exceptions that does have little in common except the fact that they belong to a particular framework.
(packages are supposedly used for just that.)
It is perfectly ok to subclass RuntimeException (if the existing subclasses are not a god fit)
Document unchecked exceptions. Be conservative with checked exceptions, and don't build hierarchies.
Rod Jonhson wrote on this in Expert one-on-one J2EE design and development and as in Tom's answer RuntimeException should be used for programming errors.
A good example is SQLException, lower level data access API should catch them and throw your own "SQLRuntimeException" as most of the time the calling code cannot do anything with the exception. This way, your higher level apis are not forced to catch or carry lower level exceptions in their signature, which make code simpler and more focused on the business domain.

Categories