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.
Related
What is the built in base class to handle all exceptions in Java?
Is It Exception or Throwable?
What is the difference between two builtin classes,can someone explain me.
Below image will help you to understand Exception Hierarchy
Image Ref: programcreek:
As you can see Throwable is super class of Error and Exception while Exception deals with checked and unchecked Exception.
Exception
The term exception is shorthand for the phrase "exceptional event."
Throwable:
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. For the purposes of compile-time checking of exceptions, Throwable and any subclass of Throwable that is not also a subclass of either RuntimeException or Error are regarded as checked exceptions.
The javadocs are for this. Here you can see that Throwable is the superclass for all Exceptions and Errors. Then you have checked and unchecked Exceptions, where the latter is RuntimeException and all its subclasses.
Remember to use Google when you're wondering about things like this, because all this information is widely available and easily found with a search engine.
From the javadocs:
Class Exception
java.lang.Object
|
->java.lang.Throwable
|
->java.lang.Exception
Hope this clears the doubt.
The above answered are very much informative. I just want to add:
The Master Base Class:
java.lang.Object
The Master Exception Class:
java.lang.Throwable
The Master Exception Class extends Throwable:
java.lang.Exception and java.lang.Error
The Unchecked class extends Exception extends Throwable:
java.lang.RuntimeException
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.
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.
I am trying to understand the Error class in Java.
I have a good understanding of the Exception class, but can't find examples of code for the Error class. I've tried searching the web and also the java.sun website, but I'm not finding anything useful to help me understand this better.
How do I use the Error class in programs and where do we have to use that?
You don't use Error in your code.
An Error is a specific kind of Throwable, just as Exception is.
Throwable is the base class that defines everything that can be thrown.
Exception is the common case. It is about problems that occur during the execution of your program.
RuntimeException is a special case: it's unchecked (i.e. it need not be declared by a method and the compiler doesn't force you to catch it).
Error is the "rare" case: it signifies problems that are outside the control of the usual application: JVM errors, out of memory, problems verifying bytecode: these are things that you should not handle because if they occur things are already so bad that your code is unlikely to be able to handle it sanely.
You should not attempt to correct the situation that resulted in an Error. You might want to catch it in order to log it and then rethrow it (see the JavaDoc of ThreadDeath for an example on why you need to rethrow it (thanks to #krock for the heads-up)).
There is no other reason to throw any Error (i.e. don't create an Error on your own and throw it, if you think you want to do that, use an Exception or a RuntimeException instead).
If you take a look at the Javadoc here there is a good explanation:
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.
Concerning the usage you also have this:
A method is not required to declare in its throws clause any subclasses of Error that might be thrown during the execution of the method but not caught, since these errors are abnormal conditions that should never occur.
Error
Error a subclass of "Throwable" class is thrown by java runtime system and indicate some unrecoverable conditions during the execution of the programs
Once thrown difficult to recover from it and the application get to halt.
Eg..,java.lang.StackOverflowError and java.lang.OutofMemoryError
// An example code which throws StackOverflowError
public class ErrorDemo
{
public void method1()
{
this.method2();
}
public void method2()
{
this.method1();
}
public static void main(String sri[])
{
ErrorDemo k= new ErrorDemo();
k.method1();
}
}
In this code from main method we are calling method1 and from method1 a call was made to method2 and again from method2 we are calling method1 means we created a continous loop which doesn't goes to end and finally a critical error StackOverflowError is being thrown.
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");
}
}
}