From Effective Java "DOCUMENT ALL EXCEPTIONS THROWN BY EACH METHOD"
It should be noted that documenting all of the unchecked exceptions that each
method can throw is an ideal, not always achievable in the real world. When a
class undergoes revision, it is not a violation of source or binary compatibility if
an exported method is modified to throw additional unchecked exceptions.
Suppose a class invokes a method from another, independently written class. The
authors of the former class may carefully document all of the unchecked
exceptions that each method throws, but if the latter class is revised to throw
additional unchecked exceptions, it is quite likely that the former class (which has
not undergone revision) will propagate the new unchecked exceptions even
though it does not declare them.
I fail to understand how can former class propagate the new unchecked excpetions ? The java language doesn't mandate the caller to catch and propagate unchecked exceptions .
It will propagate it precisely because exceptions are either caught or propagated. If not caught, an exception propagates:
public void caller() {
callee();
}
public void callee() {
throw new RuntimeException();
}
In the above example, the exception thrown from callee() will be propagated by the caller() method, since caller() doesn't catch it.
Well, if you don't catch the unchecked exceptions they propagate automatically.
#Geek ... yes java language does not mandate to handle unchecked exceptions and if you do not handle any unchecked exceptions. then Java Virtual Machine(JVM) will handle all the exception thrown by the program execution.
If called method does not handle Exception, then Exception will propagate to Calling method. If Calling method does not handle Exception, then Exception will propagate to Java Virtual Machine and default exception handler will come into effect.
Related
Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
This question does not appear to be about programming within the scope defined in the help center.
Closed 9 years ago.
Improve this question
The Java specification requires that if an exception is thrown, it is either handled by a try/catch statement, or that the function is declared with "throws XYZException". This has the exception of RuntimeException, where it is OK if this is thrown without being caught.
This might sound like a matter of opinion, but the more I think about it, the more it seems really counter-intuitive:
Why is it that we have a RuntimeException extending Exception?
When I first started doing Java, I thought ALL exceptions had to be caught in that way, and it made sense because all exceptions extend Exception. It seems like a violation of OOP to have a RuntimeException exception exception :P. Since RuntimeException makes throws kinda redundant, why didn't Java allow all exceptions at runtime in the first place, adding a throws only when you want to force the caller to handle that type of exception?
Examples:
void noThrows() {
throw new Exception();
}
... no errors.
void hasThrows() throws AnyBaseOfXYZException {
throw new XYZException();
}
... no errors.
void testFunction() {
hasThrows();
}
... fails since "hasThrows" throws AnyBaseOfXYZException, and this is not handled
void testFunction() {
try {
hasThrows();
} catch (AnyBaseOfXYZException e) {
...
}
}
... no errors.
I'd thought about maybe some kind of "CompileTimeException" that extends Exception, but when you give it enough thought, it just can't work without being as ugly as RuntimeException.
Basically, why did Java decide to force all exceptions to require throws except for RuntimeExceptions, when all exceptions could be runtime exceptions except when otherwise stated with throws?
Firstly, the base class of all things that can be thrown is Throwable (not Exception).
Under Throwable are two subclasses: Exception and Error.
Under Exception is RuntimeException.
Of these 4 main classes, RuntimeException and Error are unchecked (may be thrown without having to be declared as being thrown).
The idea behind RuntimeException being unchecked is that it's typically a programming error and that normal good practice should avoid them (eg ArrayIndexOutOfBoundsException or NullPointerException) and to require them to be caught would clutter up the code massively.
The reason Errors are unchecked is that basically, there's nothing you can to about it if one happens, eg OutOfMemoryError etc.
That leaves all other Throwables, ie subclasses of Exception, must be declared as thrown or caught. The idea behind this is that checked exceptions can be "handled by the caller". eg FileNotFoundException (we know what this means and should know what to do if we get one).
The Java designers didn't always get this right. SQLException is checked, but there's no realistic way to recover - do I have a syntax error in my query? is the database refusing conections? who knows, but I do know I can't "handle" it.
In some cases you want to have a catch that catches all exceptions: checked and unchecked.
Java's design decision allows you to achieve that with catch (Exception e) { ... }
If unchecked exceptions (exceptions that extends RuntimeException) were not extending Exception then you had to use two catch clauses.
This might be related to topic of check and uncheck exception. From RuntimeException
RuntimeException and its subclasses are unchecked exceptions. Unchecked exceptions
do not need to be declared in a method or constructor's throws clause if they can
be thrown by the execution of the method or constructor and propagate outside the
method or constructor boundary.
Check exception is to be use for case that recoverable when the program is executed. So it makes perfect sense to force programmer writing the class to declare it in a method definition. By doing so the caller will be force to catch it or re throw it.
However uncheck exception is for a case that is unrecoverable and thus it is better to terminate. This case is rarely happen (usually happen when the code is still being developed) and thus this usually indicate a programmer error or a very fatal bug that usually need to fix by the class writer and is not recoverable by the client of the class.
How come I can have
public void someMethod() {
throw new UnsupportedOperationException();
}
but not
public void someMethod() {
throw new throw new IOException();
}
The first is fine, the second generates the compile error "unhandled exception type IOException".
All things that can be thrown are Throwable. There are two types of Throwable:
Exception
Error
One subclass of Exception is RuntimeException, which is "unchecked" - meaning you don't have to declare or catch them. These are generally for "programming errors", like NullPointerException or ArrayOutOfBoundsException.
Errors are also "unchecked" and are for "unrecoverable" situations, such as OutOfMemoryError etc.
Any Throwable not a subclass of Error or RuntimeException is "checked" and must be declared as thrown or caught.
There are two types of exceptions in java; checked and unchecked.
You have to catch or specify that your method throws checked exceptions. That's the case in your second example with IOException.
http://docs.oracle.com/javase/tutorial/essential/exceptions/runtime.html
Because RuntimeExceptions and its subclasses are "unchecked" exceptions and do not need to be declared thrown, or caught. Checked exceptions do.
JLS 11, Exceptions covers exceptions in exhaustive detail, JLS 11.2, Compile-Time Checking of Exceptions discusses the differences at a high level.
IOException is a checked exception while UnsupportedOperationException is a RuntimeException (unchecked). Checked exceptions must be caught or rethrown.
http://java.sun.com/docs/books/jls/second_edition/html/exceptions.doc.html
Yo need to look at the difference between check and unchecked exceptions.
UnsupportedOperationException is a RuntimeException which is a type of unchecked exception. These are exceptions that arise during the execution of a program and indicate a state that is unlikely to be recovered from.
Checked exceptions, the type you must handle in some way, are exceptions that you can probably write code to handle gracefully.
The Java Language Specification, section 11.2.5, states it very well:
The runtime exception classes (RuntimeException and its subclasses)
are exempted from compile-time checking because, in the judgment of
the designers of the Java programming language, having to declare such
exceptions would not aid significantly in establishing the correctness
of programs.
There are some good explanations of the idea behind the two types. The Java Tutorial has a page titled Unchecked Exceptions — The Controversy, and if you want a more lengthy discussion see Checked or Unchecked Exceptions?
IOException is a "checked" Exception and must be handled.
In the Below example if RuntimeException is replaced with some other exception then compiler throws the compilation error. But for Runtime Exception's it is not throwing anything. Why? Please explain.
class A {
public void process() {
System.out.print("A,");
}
}
class B extends A {
public void process() throws RuntimeException {
System.out.print("B,");
throw new RuntimeException();
}
public static void main(String[] args) {
A a = new B();
a.process();
}
}
RuntimeExceptions are what we call "unchecked exceptions".
This means, the compiler does not check whether they're caught in code.
The reason for this is, we have some exceptions that we often prefer to not have to handle or declare. For instance, NullPointerExceptions can potentially be thrown at so many places in the code, that it's more convenient if we only handle them, if we explicitly decide to.
See also:
In Java, when should I create a checked exception, and when should it be a runtime exception?
Unchecked Exceptions — The Controversy
Java unchecked/checked exception clarification
This has to do with checked vs unchecked exceptions. Here is another brief explanation
That's why it's called RuntimeException :)
Seriously, RuntimeException (all all exceptions inheriting from it) are called "unchecked exceptions" and the whole point is that they are NOT checked by the compiler.
This is required of a compiler, due to the following requirement in the Java Language Specification
11.2.5 Why Runtime Exceptions are Not Checked
The runtime exception classes
(RuntimeException and its subclasses)
are exempted from compile-time
checking because, in the judgment of
the designers of the Java programming
language, having to declare such
exceptions would not aid significantly
in establishing the correctness of
programs. Many of the operations and
constructs of the Java programming
language can result in runtime
exceptions. The information available
to a compiler, and the level of
analysis the compiler performs, are
usually not sufficient to establish
that such run-time exceptions cannot
occur, even though this may be obvious
to the programmer. Requiring such
exception classes to be declared would
simply be an irritation to
programmers.
For example, certain code might
implement a circular data structure
that, by construction, can never
involve null references; the
programmer can then be certain that a
NullPointerException cannot occur, but
it would be difficult for a compiler
to prove it. The theorem-proving
technology that is needed to establish
such global properties of data
structures is beyond the scope of this
specification.
Unlike checked exceptions, runtime exceptions (or unchecked exceptions) do not define a contract between the caller and the called method, for they usually indicate an erroneous condition, that is often resolved by the caller if it were to obey the contract.
If a compiler were to be given the task of enforcing such a contract, it would result in additional complexity (in the language itself and in the code that people write). Imagine, enforcing every method to check for null arguments and requiring programmers to throw such exceptions (and also declare such exceptions in the throws clause). The easier way out, is to specify a contract that states that a method will not operate on null arguments and that a caller should expect to catch NullPointerExceptions; if the caller wants to avoid this scenario, it must check the arguments before invoking the method.
The reason for that is the fact that checked exceptions declared for the overriding method must match with the signature of the method overridden. Otherwise the code won't compile due to the method signature mismatch. It is fine when you declare unchecked exceptions in overriding method, because these exceptions as the name suggest are not checked by the compiler.
Any difference about those two?
Exceptions are for errors in the program logic. Error are used by the JVM to signal that something is wrong with the environment such as an OutOfMemoryError or IncompatibleClassChangeError. ThreadDeath is used to kill Threads. Throwable is a super class over all of these.
In normal program logic, you should never throw nor catch Throwables or Errors. The main reason I can think of for catching a Errors is this: You are using your own class loading system and want to isolate broken plugins.
The JavaDoc for ThreadDeath for example says:
An application should catch instances of this class only if it must clean up after being terminated asynchronously. If ThreadDeath is caught by a method, it is important that it be rethrown so that the thread actually dies.
The Throwable class is extended both by the Exception class and the Error class, so by using throws Throwable you are actually saying that your method may not only throw an Exception but also an Error. The difference between the two according to the documentation is that Exceptions are
conditions that a reasonable application might want to catch
while errors indicate
serious problems that a reasonable application should not try to catch
See here for more details.
This is the hierarchy
java.lang.Object
java.lang.Throwable
java.lang.Exception
Throwable Java Doc
The Throwable class is the superclass of all errors and exceptions in the Java language. Only objects that are instances of this class (or one of its subclasses) are thrown by the Java Virtual Machine or can be thrown by the Java throw statement. Similarly, only this class or one of its subclasses can be the argument type in a catch clause.
Instances of two subclasses, Error and Exception, are conventionally used to indicate that exceptional situations have occurred. Typically, these instances are freshly created in the context of the exceptional situation so as to include relevant information (such as stack trace data).
Exception Java Doc
The class Exception and its subclasses are a form of Throwable that indicates conditions that a reasonable application might want to catch.
Please read the doc, it explains.
A Throwable could be a Error or Exception.
From Java doc:
An Error is a subclass of Throwable that indicates serious problems that a reasonable application should not try to catch. Most such errors are abnormal conditions.
The class Exception and its subclasses are a form of Throwable that indicates conditions that a reasonable application might want to catch.
If a Throwable could only be an Error or an Exception, there would be no difference between throws Throwable and throws Exception for a method, as Error can be always thrown, even if it was not declared (like RuntimeException, too).
But a method declared with throws Throwable can also use throw new Throwable("example");, or something like this:
class CannonBall extends Throwable {}
throw new CannonBall();
There normally is no reason to do something like this, so in practice throws Throwable and throws Exception are equivalent.
While reading about exception, I will always come across checked exceptions and unchecked exceptions, So wanted to know how to distinguish that which is what?
Edit: I want to know if i create any exception class then how can i create as a checked or as an unchecked?
and what is the significance of each?
All Throwables except subclasses of java.lang.RuntimeException or java.lang.Error are checked. Properly, in Java, "exceptions" are subclasses of java.lang.Exception, "errors" are subclasses of java.lang.Error and java.lang.Throwable is not usually subclassed directly.
Programs are not supposed to create their own Error subclasses (though the documentation is rather ambiguous on that) so generally you always create Exceptions, using a RuntimeException if you don't want it to be checked.
To know at run-time if you have a checked exception you could use:
if(throwable instanceof Exception && !(throwable instanceof RuntimeException)) {
// this is a checked Exception
}
A checked exception is one which must be either handled in a catch clause, or declared as being thrown in the method signature; the compiler enforces this. Generally, one uses checked exceptions for exceptions which should be handled by the calling code, while unchecked exceptions are for conditions which are the result of a programming error and should be fixed by correcting the code.
That said there is much debate in the Java community about the efficacy of using checked exceptions vs. unchecked exceptions everywhere - a subject way to deep to discuss in this answer.
EDIT 2012-10-23: In response to comments (which are quite valid), to clarify, the following would be what is required to determine if a captured Throwable is a checked Throwable as opposed to a checked Exception:
if(obj instanceof Throwable && !(obj instanceof RuntimeException) && !(obj instanceof Error)) {
// this is a checked Throwable - i.e. Throwable, but not RuntimeException or Error
}
If the object in question is known to be an instance of Throwable (e.g. it was caught), only the second part of the above 'if' is needed (e.g. testing for Throwable is redundant).
See the Java Language Spec, chapter 11:
The unchecked exceptions classes are the class RuntimeException and its subclasses, and the class Error and its subclasses. All other exception classes are checked exception classes. The Java API defines a number of exception classes, both checked and unchecked. Additional exception classes, both checked and unchecked, may be declared by programmers.
You could check this via instanceof at runtime, though I don't really see where this would be useful.
As to the second part of your question:
checked exception represent expected error conditions, which can occur during normal program execution and therefore always have to be handled programatically (which the compiler enforces)
unchecked exception represent unexpected error conditions and signify an abnormal state of your program, due to invalid input, bugs or runtime restrictions (eg memory); the compiler won't force the programmer to handle these, ie you only have to care for them if you know of their occurrence
Java checked vs unchecked exception
Error is internal VM error and usually you can not manage it.
Exception - you are able to catch and handle it
Checked vs Unchecked
checked exception is checked by the compiler and as a programmer you have to handle it using try-catch-finally, throws
unchecked exception is not checked by the compiler but you optionally can manage it explicitly
IntelliJ IDEA's Type Hierarchy tool is useful when you want to find more
If the exception class is a subclass of RuntimeException, it's not checked and does not have to be declared for functions or caught, etc. Error exceptions also do not have to be declared/caught. Is that what you're asking?
Quite sure this will have been asked and answered before, but for the sake of it, it is covered quite nicely here: http://www.javapractices.com/topic/TopicAction.do?Id=129.
Strictly speaking, unchecked exceptions will always extend RuntimeException whereas checked exceptions do not. The mentioned link explains when to use either.
As their name indicates, callers are obliged to deal with checked exceptions, typically handling them (try/catch) or passing them further up the stack. Unchecked exceptions are usually deemed to be caused by elements outside of the caller's control.
package practice;
import java.io.IOException;
class Practice
{
public static void main(String args[])
{
Exception n=new NullPointerException();
if(n instanceof RuntimeException)
{
System.out.println("this is a runtime(unchecked) exception");
}
else
{
System.out.println("this is not a compiletime(checked) exception");
}
}
}