Sunday, August 1, 2010

Except exceptions!!

Exception in layman term is abnormal behaviour of your program. A bunch of things can lead to exceptions, including hardware failures, resource exhaustion, and good old bugs. When an exceptional event occurs in Java, an exception is said to be thrown. The code that’s responsible for doing something about the exception is called an exception handler, and it catches the thrown exception.

>>> Order of catch block matters.

>>> The finally clause is used to provide the capability to execute code no matter whether or not an exception is thrown or caught.

>>> A checked exception is some subclass of Exception (or Exception itself) excluding class RuntimeException and its subclasses, which are forced by compiler to be checked. Example: IOException.
Unchecked exceptions are RuntimeException and any of its subclasses. Class Error and its subclasses also are unchecked. The compiler doesn't force client programmers either to catch the exception or declare it in a throws clause. In fact, client programmers may not even know that the exception could be thrown. Example: ArrayIndexOutOfBoundsException. Errors are often irrecoverable conditions.

>>> Throwable is the base class of Error and Exception.

>>> The throw keyword denotes a statement that causes an exception to be initiated. The throws keyword is a modifier of a method that denotes that an exception may be thrown by the method.

>>> Error's are generally system's error and Excepion are programmer's error.

>>> Finally block get executed whether exception is thrown or not. Even if there is return statement in try block, finally block get executed after the return statement.

Defensive Coding for NPE -
1. If name is null
don't do - if(name.equals("Peter")) - chances to get NPE
do - if("Peter".equals(name))
2. Always return empty collection instead of null like
return Collections.EMPTY_LIST;
3. Always check for null before carrying out operation on the object and define alternate course of action.

No comments:

Post a Comment