Error vs Exception in java


Error vs Exception



An Error "indicates serious problems that a reasonable application should not try to catch."
while
An Exception "indicates conditions that a reasonable application might want to catch."

Error and Exception both are extending Throwable but usually Error is thrown by JVM in a scenario which is fatal and it is not possible for the application to recover from that error. For instance OutOfMemoryError. Even application can raise an Error but its just not a good practice. Application should use checked exceptions for recoverable conditions and runtime exceptions for programming errors.Error is something that most of the time you cannot handle it but exception was meant to give you an opportunity to do something with it. like try something else or write to the log.

Exception is generally divided into two categories e.g. checked and unchecked Exceptions.

1.    Checked Exception has special place in Java programming language and require a mandatory try catch finally code block to handle it.
2.    On the other hand Unchecked Exception, which are subclass of RuntimeException mostly represent programming errors. Most common example of unchecked exception is NullPointerException in Java. 

Checked exceptions are the those from which a program can be recovered programmatically. Examples include FileNotFoundException, ParseException, etc.
A programmer is expected to check for these exceptions by using the try-catch block or throw it back to the caller. On the other-hand we have unchecked exceptions. These are those exceptions that might not happen if everything is in order, but they do occur. Examples include ArrayIndexOutOfBoundException, ClassCastException, etc.

Many applications will use try-catchor throws clause for RuntimeExceptions & their subclasses but from the language perspective it is not required to do so.

Errors are also unchecked exception & the programmer is not required to do anything with these. In fact it is a bad idea to use a try-catch clause for Errors. Most often, recovery from an Error is not possible & the program should be allowed to terminate. Examples include OutOfMemoryError, StackOverflowError etc. Errors can not handled by programmers because even if you catch them you can not recover from them like during OutOfMemoryError, if you catch it you will get it again because Garbage Collector may not be able to free memory in first place. On the other hand Exception can be caught and handled properly.

If you still have any question you can reach me any time through email (jigyasu2010@hotmail.com)

Comments

Popular posts from this blog

How Method Overloading Helping in Java - Part 9

Important Java Interview Questions - Part 7

Access Modifiers in java