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).
Related
This question already has answers here:
Should methods that throw RuntimeException indicate it in method signature?
(7 answers)
Closed 4 years ago.
Let's say I have the following code:
public void methodOne(String argumentOne) {
methodOne(argumentOne, false);
}
public void methodOne(String argumentOne, boolean equality) {
//App logic here
}
And if the app logic throws an exception (say IllegalArgumentException/Parse Exception), and i would like to catch this in the caller method, should the "throws IllegalArgumentException" be added in all the method identifier or only on the base method identifier? Is there any advantage over this?
Throwing a checked exception means you expect the caller to be forced to think about how to handle that exception. You should only do this when:
This is a deliberate, desirable action in your mind.
You have some idea how you expect the caller to deal with a checked exception. Ideally, you have documented what you expect them to do with the exception.
Thus it's a very bad idea to
declare "throws" an exception which is never actually thrown. This just causes confusion and get the developer into the habit of ignoring your exceptions as they have no value.
throw a checked exception when it is unlikely to be a reasonable way to recover from it. An unchecked exception might be better in that case.
I prefer to add throws clauses for unchecked exceptions as a form of documenting what can go wrong and what it means without forcing the caller to handle those exceptions.
Additionally, you should try to add meaningful messages to each Exception/Error to make it easier for a developer to work out how to fix the code or configuration.
i would like to catch this in the caller method, should the "throws IllegalArgumentException" be added in all the method identifier or only on the base method identifier?
Only add it to the methods which can actually throw the exception.
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.
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.
The type of an exception is often enough to handle it properly (for example you try to open a file and get a FileNotFoundException). However there are cases where you might catch multiple exception of the same type. For example, an IllegalArgumentException that can be caused by more than one argument. The IllegalArgumentException does not add any additional methods (or public fields) to the Throwable interface (accoding to the online javadoc) which means that the only information that you can rely on are the nested exception (which may or may not exist) and the message (which is for human consumption).
I don't like the idea of extending IllegalArgumentException to add structured information to it, because other people would have to learn the new class. And I don't like the idea of littering projects with very specific exception classes.
Using the message field is also a bad idea because it's not meant for programmatic access.
I think IllegalArgumentException should have included details such as the class function and argument(s) in question. And in general custom exceptions should provide additional detail (other then just their type) for a more fine grained exception handling.
What are considered generally the best practices for designing exception classes, and handling exceptions of the same type?
As a general rule, I think it is ideal to have one class of exception per "type of action a caller might reasonably want to take". Of course, for one's own custom exceptions there could be a boolean or enum field providing some extra disambiguation, rather than creating trivial subclasses.
In your specific case I'm not convinced that trying to handle the exception is a good idea. RuntimeException and its subclasses usually represent coding issues, and the same is true of IllegalArgumentException. If the argument is illegal it shouldn't be passed in in the first place.
If you're in a situation where you're not sure if an argument is valid (maybe it's user input, or maybe you don't know the specific object you're calling the method on) then a better approach would be to have some way of checking the validity of the argument before passing it. Rather than say "do this" and catch the exception, ask "can I do this?" before calling.
Exception classes should be designed so as to provide all that is needed when they are caught. Note that try/catch statements are actually a form of type switch, so in general it is cleaner to create additional exception classes rather than confuse program logic by nesting too many if's within catch clauses.
It has to be said that catch clauses are not very convenient if you want to organize your error handling code in an object oriented fashion, so there are different trade offs to keep in mind.
Note that standard exception classes do have information available on what piece of code caused the exception, even though I would not advise you to base on it your error handling logic.
If the current exception was thrown in a catch clause for a different exception this should be available with the getCause() method, while the getStackTrace() should provide access to the stack of calls that were active when your exception was thrown.
Again I don't advise you to use this information except for debugging purposes.
Its true that the predefined exception classes are very general. But if you want more specific details about the exceptions then you should go for user defined exceptions. you should create your own exception classes with any level of details!
here is the pseudo code:
public class TooManyArguments extends exception{
public String toString(){
return ("..whatever information you want to give for this exception..")'
}
}
and whenever you encounter exceptional situation throw an instance of this class
throw new TooManyArguments();
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.