This question already has answers here:
In Java, when should I create a checked exception, and when should it be a runtime exception? [duplicate]
(14 answers)
Closed 4 years ago.
I am doing a code review and I have came across this method definition:
public void something() throws RuntimeException
Is there a rational reason to write 'throws RuntimeException' in Java?
RuntimeException is unchecked exception and therefore can be thrown from any place in the code. Saying "Hey, this method can throw RuntimeException" and knowing that any piece of code can do so may be redundant. The only reason I can think of, you would like to make it explicit is for documentation purposes, eg. "Throws RuntimeException when some specific thing happens", but then it probably belongs to javadoc, not to method signature.
Everything is context-dependent, of which you shared none; but on a general note in may be said that this very rarely makes sense. Methods declare unchecked exceptions for documentation purposes, but these are normally specific exceptions carrying some domain-specific meaning. Declaring to throw a completely generic unchecked exception is thus quite hard to justify, although I cannot say there is absolutely no situation where it may make sense.
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.
This types of exceptions depend directly of code, for example, "ArrayIndexOutOfBoundsException".So, if you don't use arrays, arraylists, casting or something what could throw a RuntimeException, it wouldn't be neccesary to write that.
Any method can throw RuntimeException, like NullPointerException being most common. So if a method throws RuntimeException (or it's subclass), it's usually not put that in method signature.
So according to me, it just shows inmaturity of the programmer as it doesn't add any value. Though, it's not asked but even the method name i.e. something() is fishy. It doesn't convey any meaning to the reader.
Related
When I throw checked exceptions from a method should I just declare the super class of the exceptions in the method signature or all the different types? If I have the following exceptions:
private class SuperException extends Exception {
}
private class SubExceptionOne extends SuperException {
}
private class SubExceptionTwo extends SuperException {
}
Should the method signature be:
void confirmAccount() throws SubExceptionOne, SubExceptionTwo;
or
void confirmAccount() throws SuperException;
In the last method signature, how do I tell other developers what exceptions that could be thrown from the method? If the different sub types need different handling?
The interface should be as stable as possible. So probably Super. Many libraries use the "Super" strategy, because exception specs cause far more annoyance in maintainability than readability or safety they add. Even the IOException is a Super that nearly all Java library code uses instead of declaring more specific exceptions. (But when they do declare more specific exceptions, it's because the contract is that more general IOExceptions won't be thrown. Read on.)
You might list Sub1 and Sub2 if you really do want to say each of those exceptions can be thrown, but don't want to say that any derivative of Super can be thrown. Perhaps Sub1 is NumberCrunchException and your method calls crunchNumbers() and users of your method can be assured that's the only exception-ful thing your method does. In that case the specific strategy is better.
If the different sub types need different handling, then definitely declare the two different exceptions. Never expect the developer using your method to guess that you are actually throwing different types of exceptions.
If you declare two distinct exceptions, and the user knows from the Javadoc that they are actually descendents of the same class, the user may choose to catch them both with a catch (SuperException e) rather than two individual catch clauses. But it depends on the user's choice.
If you don't declare them separately, your IDE is not going to add the appropriate #Throws to your Javadoc comment. And your Javadoc will therefore only indicate that you're throwing SuperException, which will leave the user in the dark. Solving this by just putting it in the text of the comment is not a real solution. If any tool is using reflection to determine what your method throws, it will not see the individual exceptions in the array returned from Method.getExceptionTypes().
If the functionality expected of the different exceptions is more or less the same and it's just a matter of how they will appear in the logs, it may be better to just use the parent exception, with different messages.
The throws clause is there to convey useful information to the calling method about what might go wrong during invocation of this method. That means that how specific you are will depend on how much information you want to convey; and that will be application-dependent.
For instance, declaring throws Exception is almost always a bad idea: the information this conveys is just "something might go wrong", which is too vague to be useful. But whether calling classes are going to need perfectly fine-grained information in the throws clause is something you need to decide by looking at your program. There's no set answer.
Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 9 years ago.
Improve this question
I'm defining a new interface API... admittedly not something I do all that often. I'd like to define the interface methods to throw an Exception to allow some flexibility for the implementers. They can then choose to throw an Exception, throw a more specific subclass of Exception, or throw nothing at all. I've read a couple of times that while its good to allow implementing classes this flexibility, it's also bad to define the interface method with "throws Exception". Instead, it's recommended to subclass Exception (e.g. MyException) and throw the subclass. The explanations for this practice were lacking in detail, so can someone elaborate on this best practice please? Thanks.
I can appreciate trying to give the implementers some flexibility, but the exception is part of the API, so you should put some thought into what (checked) exception(s) makes sense.
By saying throws Exception, you are not helping the clients of the interface understand what kinds of failures are expected to give them a chance to react to them appropriately. You can consider akin to accepting a method parameter of Object to allow implementers to decide what arguments they can accept. Its good for the implementer, but a nightmare for the clients of the interface.
Better have an idea what exceptions you need to throw later.
There's the so called Liskov substitution principle, which recommends not to throw exceptions in subclasses that would not be thrown by the super class.
Liskov substitution principle aka. design by contract:
http://en.wikipedia.org/wiki/Liskov_substitution_principle
If you are uncertain which Exception need to be thrown, use "throws Exception" (even if it is uncool). Just do not allow unexpected behaviour by implementing classes when they throw exceptions where they weren't planned by you.
The worst case would be a programmer who desperately throws runtime exceptions because of a lack of throws-declarations.
I prefer to throw Java standard subclass of RuntimeException. This gives the flexibility of allowing the Exception to propagate or be caught without having references to your API.
There are many subclasses to choose from http://docs.oracle.com/javase/7/docs/api/java/lang/RuntimeException.html
Often I use IllegalStateException or IllegalArgumentException
Think of checked exceptions as optional return values. The API whose methods return Object is understandably rare, and the same principle should apply for checked exceptions.
The reason for saying that an interface method declaring to throw the base class Exception is bad practice is because it would in fact make throwing an instance of that very base class a legal implementation of the interface, which is what you clearly want to avoid.
This is why you would only use specialized/custom exception types in your signatures.
I wouldn't go as far as saying that an interface should not declare a throwing of any Exception in advance, as someone said in his answer previously, because the interface is in fact not free floating.
You, as the one declaring the interface, invoke or use the methods in a certain way, and you make assertions on how the methods will be used by your side of the code.
It is in fact a contract that you create. And exceptions are a part of that contract. In fact the one using the interface (not the one implementing it) will be done with his work way before an implementation may exist.
in general, throwing an exception means one of the two options:
asking the caller to take an action based on something that happened, usually hoping he has a broader / better understanding of the situation to take a decision
Notify the caller that the action failed beyond repair
focusing on the first type throwing specific exceptions is a good idea and the called can than do:
try {
} catch (ServerIsBusyException ex) {
// wait 10 sec and continue / try another server
} catch (BadUserNameException ex2) {
// try another name
} ....
second type is usually RuntimeException s that means an unexpected situation
see a good explanation in this answer
This question already has answers here:
Checked vs Unchecked exception
(7 answers)
Understanding checked vs unchecked exceptions in Java
(21 answers)
Closed 9 years ago.
I've been doing some pure Java development recently, and I'm using an external lib that exposes a small number of methods, each of which have the possibility of throwing an Exception.
Eclipse won't let me compile my program unless I wrap each of those calls in a try-catch block. So far, no big deal.
Then I noticed some things, like ArrayList.add(), which throws IndexOutOfBoundsException. How is it that I can call something like this without needing to wrap it in a try..catch? Obv, in this particular case, it would be incredibly irritating if you had to do it each time, but how and why is try-catch enforced in some situations, but not others?
Unchecked exceptions (subclasses of Error or RuntimeException) need no try..catch block, and when there is no try...catch, the method need not to declare itself to be throws (you can, of course, and some consider declaring throws to be a good practice) . On the other hand, checked ones do need the try...catch, or declares throws.
IndexOutOfBoundsException is an unchecked exception, i.e. it extends RuntimeException or Error, or sub class of either, therefore a try/catch block is unnecessary. From the docs:
Checked exceptions are subject to the Catch or Specify Requirement. All exceptions are checked exceptions, except for those indicated by Error, RuntimeException, and their subclasses.
In contrast, checked exceptions require a try/catch block otherwise a compiler error will result.
This question already has answers here:
Closed 11 years ago.
Possible Duplicate:
What can you throw in Java?
Why can't I take an Exception in a reference of Object.
I mean consider the following code:
try{.......}
catch(Object ex){.......}
It shows an error, where as we knows that it's possible for all the objects of any class to be referenced by Object.
The Java Language specification says that only Throwables can be thrown.
http://java.sun.com/docs/books/jls/third_edition/html/exceptions.html#44043
Every exception is represented by an instance of the class Throwable or one of its subclasses; such an object can be used to carry information from the point at which an exception occurs to the handler that catches it.
The language could have been defined differently, but Java tends to define a base type for any kind of thing that is intended to be used in a particular way and defines methods in that base class to support common patterns. Throwable in particular supports chaining and stack trace printing. It would not be possible to chain exceptions as easily if the only thing you knew about an exception was that it was a reference type.
You can assign a reference of an Exception to an Object without a problem. But Objects can't be thrown or catched.
That only works for Throwables.
So that in catch block you can be sure to get some details on exception like getCause(), getMessage(), getStackTrace(). If its generic Object, you wont have access to these methods without explicit casting, and you wont be still sure that these method actually exist. As its instance of Throwable, you are sure that you can retrieve these details from exception (the object in the catch).
You can't because only subclasses of Throwable can be thrown. I suppose it would be possible for them to have allowed you to use Object in a catch block, instead -- the only superclass of Throwable -- but what would be the point, since the variable would always refer to a Throwable instance.
Maybe you are coming from C++ where anything can be thrown, even an int. Java exceptions extend Throwable. Object does not extend it (of course).
What's the difference between implicit exception and explicit exception?
If I declare catch block like: catch(Exception e). Is this implicitly declaring an exception, or explicitly?
Thanks in advance.
I don't believe there's any such term as "implicit exception" or "explicit exception". Are you thinking checked and unchecked exceptions perhaps?
I've just downloaded the language specification as a PDF, and the phrases "implicit exception" and "explicit exception" don't exist anywhere within it.
Could you say where you came across the terms?
I think implicitly instantiating an object is done without explicitly calling a constructor. I don't think you can do that in Java.
Example:
throw new Exception();
calls a constructor and then throws the newly created Exception object.
This only applies to the first part of your question:
The terms explicit and implicit exceptions do exist and relate to how a Java virtual machine handles exceptions. From the end-user (Java programmer) view, they are the same (besides the obvious performance benefit).
Explicit exceptions are ones explicitly checked for by the JVM. For example every array indexing operation you do, is explicitly checked for being in range by the JVM.
Implicit exceptions are ones that are thrown in the aftermath. For example NullPointerException and StackOverflowException are thrown in the handler routine for the segmentation fault. This is quite a performance boost as the JVM gets signaled by the OS instead of having to incur an overhead on every operation that might throw.
Neither. Catching is not declaring an exception. Declaring an exception happens on the method:
public void someMethod() throws Exception.
I'm not sure what you mean by implicit vs. explicit. You probably mean something like the difference between a runtime and checked exception, but you could also a mean a method which throws a Runtime exception, which is optional.
public void someMethod() throws NullPointerException
The throws in that case is purely optional, since it is a Runtime exception, nothing should happen differently.