views:

83

answers:

5

Hi,

What are the Runtime exceptions and what are Checked/Unchecked Exceptions and difference between Error/Exception.Why these many types? Instead Java may simply follow a simple design(just try/catch all types) to handle an abnormal condition in a program?

A: 

Duplicate of this

Dan
No I am not only seeking for difference .I want to know Why these many such types present in java?
JavaUser
+1  A: 

Have you read the Sun Java Tutorials lesson on exceptions? That's probably a good place to start.

Isaac Truett
+5  A: 

Throwable is at the top off all exceptions. Underneath Throwable you have Error and Exception. Underneath Exception you have RuntimeExcdeption.

Java has two types of exceptions - checked and unchecked. Checked exceptions are enforced by the compiler (you have to declare them in the throws clause and catch them eventually). Unchecked exceptions are not enforced for catching or declaring in throws clause.

(Controversial part of the answer)

Throwable exists so that there is a parent for all exception types. You should never declare that you throw Throwable and never catch it (unless you really really really know what you are doing).

Error exists to indicate issues with the runtime environment, things that your program probably cannot recover from, such as a badly formatted class file or the VM running out of memory. You should not catch an Error unless you really know what you are doing.

Exception exists as the root for all non-programmer errors (see RuntimeException for the "exception" to this) , such as a file cannot be created because the disk is full. You should not throw, throws, or catch Exception. If you have to catch Exception make sure you know what you are doing.

RuntimeException exists to indicate all programmer error, such as going past the end of an array or calling a method on a null object. These are things that you should fix so that they do not throw exceptions - the indicate that you, the programmer, screwed up the code. Again, you should not catch these unless you know what you are doing.

TofuBeer
Nitpick: *"Exception exists as the root for all non-programmer errors"* is misleading since `RuntimeException` and its subtypes are also subtypes of `Exception`.
Stephen C
+1  A: 

@TofuBeer's answer explains clearly what the exception classes mean.

Why these many types? Instead Java may simply follow a simple design(just try/catch all types) to handle an abnormal condition in a program?

Why? Because they are necessary! Without those 4 classes, handling exceptions by broad category would be impractical.

  • How would you catch "all fatal JVM errors" without the Error class?
  • How would you catch "all exceptions that are not JVM fatal errors" without the Exception class?
  • How would you catch "all unchecked exceptions" without the RuntimeException class?
Stephen C
A: 

Runtime Exceptions provide you with the flexibility to avoid catching, declaring the exceptions.

SidCool