Saturday 3 January 2015

Checked v/s unchecked exception

Exception in java:there are three types of Exceptions:

1. Checked Exception
2. Unchecked Exception
3. Error


Checked Exception:
These are exceptional conditions that a well-written application should anticipate and recover from.
All exceptions directly inherited from Exception class are checked exception.
Please note: checked Exception is not concerned with compiler time.
We can only get compile time error and not compile time exception.

For example: FileNotFoundException: it can possible that user have entered a wrong name: possibility to enter correct name.
  
Unchecked Exception:These are exceptional conditions that are internal to the application, and that the application usually cannot anticipate or recover from.
These usually indicate programming bugs, such as logic errors or improper use of an API.
Example: NullPointerException: Let say we want to call a function for from object.But let say object is not initialized, we should not initialized that object because it can be possible that reference is of interface and it may be inherited by n number of classes/ interface.Now which implementation to initialize, how to decide that.

Error:These are exceptional conditions that are external to the application, and that the application usually cannot anticipate or recover from.
Example: OutOfMemoryException .If JVM memory get overflow, what a programmer can do... there is no way to recover.

The Java compiler forces you to either catch checked exceptions or declare them in the method signature. It was supposed to improve program safety.

Keep in mind:
java.lang.Exception is referred to as "Checked Exception"
java.lang.RuntimeException is referred to as "Unchecked Exception"

No comments:

Post a Comment