Pages

Monday 9 September 2013

Core Java - Exception Handling (FAQ's)





1.    What is Exception Handling ?

Exception is any unexpected event which disturbs the normal program flow. Programmer has to handle this exception, otherwise program will be terminated abnormally. We actually cannot avoid exceptions but we can handle exception by providing some alternative way of continuing the program flow and is called Exception Handling.






2.    What is Throwable ?

In exception hierarchy Throwable class is a root class. It has 2 child classes (Exception & Error).

Exception usually occurs due to program & are recoverable by providing alternate way of continuing the program flow. But Error occurs due to lack system resources & are not recoverable.

Example:

For computation in our program if we are using some numeric value as a input & this input is coming from some file which has junk values then we will get Arithmetic Exception which we can handle by providing alternate code or function.
This way all exceptions can be handled.

While executing the java program if server fails or memory is full then we cannot handle this and it is not an exception, rather we call it as ERROR. For memory full, we will get OutOfMemory error.
Error's are not recoverable and will end up with abnormal termination of program.



3.    What is Try-Catch ?

Being a program we should not code our program which leads to abnormal termination. So it is highly recommended to handle all possible exceptions in program.

In Try block we usually put risky code where possibility of exception is maximum & corresponding handling code is kept in Catch block.

Example:

try 
    {
      Code where possibility of exception is high (risky code)
      -------
      -------  
    }
Catch (Exception e)
    {
      Alternate code for occurred exception (Exception Handling code)
      -------
      -------
    }




4.    What are check exception & uncheck exception ?

CHECKED Exceptions:
Exceptions which are checked during compilation for smooth execution of program at run time are called check exceptions. Compiler verifies if check exceptions are handled by programmer or not, if not handled compile time error will occur.
Example:
              IOExceptions
                - FileNotFound
                - IntrruptedIOException
                - EOFException

UN-CHECKED Exceptions:
Exceptions which are not checked by compiler whether programmer has handled them or not are called Unchecked Exceptions.

Unchecked exceptions always occur during run time.
Example:
          Runtime Exceptions
              - ClassCastException
              - NullPointerException
              - ArithmeticException

Note:
All Exceptions whether checked or unchecked occurs during runtime only, no exception occurs during compilation.
All Unchecked exceptions are fully unchecked except THROWABLE & EXCEPTION.




5.    What is finally block ?

To maintain clean up code we use finally block & best thing about finally block is, it gets executed always irrespective of exceptions occurred or not & handled or not handled.

Example:

try 
    {
      System.out.println("Testing Try Block")
    }

Catch (Exception e)
    {
      System.out.println("Testing Catch Block")
    }
finally
    {
      System.out.println("Testing finally Block")
        }

If no exception occurred; output will be ==>
Testing Try Block
Testing finally Block

If exception occurred in try block; output will be ==>
Testing Catch Block
Testing finally Block


Note:
  • If return statement is specified in try block or catch block then return will be executed after finally block execution only.
  • If return statement is specified in try block, catch block & finally block then return statement in finally block will be considered.
  • So finally block will be executed always except for one condition, if we specify System.exit(0) in try block then finally block will not be executed. 
  • System.exit(0) will shuts down the JVM which will not allow any further execution of code.


try-catch-finally rule:
  1. Try block without catch block or finally block is not allowed.
  2. Catch without try block is not allowed.
  3. Finally block without try block is not allowed.
  4. From Java version 1.7, try block can be defined alone & all resources opened in try block are closed automatically by implementing AutoClosable interface which contains only close() method.



6.    What is difference between final, finally & finalize() ?

Final is a modifier applicable for variables, methods & classes.

Finally is block specified with try-catch & its purpose id to maintain clean up code to be executed always irrespective of exception occurred or not & handled or not.

Finalize() is a method called by Garbage collector just before destroying an object to perform cleanup activity. After completion of finalize() method Garbage collector automatically destroys the object.




7.    What is difference between Throw & Throws ?


Throw:

Sometimes programmer can create the exception object & can handover that object to JVM manually, to achieve this we have to use THROW keyword.

Example:
Class TestThrowKeyword
         {
            Public static void main(String arg[]) 
            {
             if(WithdrawMoney > balance)
                {
                   throw new InSufficientBalanceException();
                }
             else
                {
                   Process withdrawal request
                }
            } 
         }

Notes:
  1. Here InSufficientBalanceException is customized exception
  2. It is highly recommended to use throw keyword for customized exceptions instead of using with predefined exceptions.
  3. Once we have used throw keyword in our code, we cannot use any other statement after that, if used it will throw an compile time error saying "unreachable statement".
  4. throw can only be used with throwable types, if used without throwable types, compile time error will occur, so always extend class with throwable type (e.g. "class testThrowKeyword extends RuntimeException").



Throws:

In every java programme compulsory we have to handle checked exception for smooth execution of program at run time. If we will not handle checked exception, compile time error will occur. Their are 2 ways of handling checked exception:
1.  Try Catch
2.  Throws

Throws here plays role of delegating responsibility of exception handling to caller method or JVM. This way caller is responsible to handle that checked exception. Throws keyword is used only to convince compiler that checked exception is handled, this will avoid compile time error.

Class TestThrowsKeyword extends Exception
         {
            Public static void main(String arg[]) 
            {
             WithdrawMoney() throws IntrruptedException
                {
                      --------
                      --------
                }
             DepositMoney() throws IOException
                {
                      --------
                      --------                   
                }
            } 
         }

In above example compiler will not give any compile time error as throws keyword used for possible checked exceptions.

Note:

  • Throws keyword is applicable only to methods and constructors & cannot be used for classes.
  • Throws keyword can only be used for throwable types.
  • Try catch is recommended over throws keyword.




8.    How default exception handling works in java ?

In general when any exception raised in java program & an exception object will be created by method in which exception is raised and is handed over to JVM.
JVM checks if that raised exception in handled in program or not, if exception is handled in method then handling code will be executed otherwise JVM will check if exception is handled in caller method.
This is process continue till main() method. If exception is not handled then JVM terminates main() method and handover exception object to Default Exception Handler.

Default Exception handler prints exception details on console and terminates the program abnormally.

Below are the 3 methods used by default exception handler to print exception information.

1.   printStackTrace()  ==> It prints (name of exception, description of exception & stack trace).
                                           This is default method to print exception information.
2.   toString()              ==> It prints (name of exception & description of exception).
3.   get message()       ==> It prints (description of exception)

Note:
Above 3 methods are defined in Throwable class.





More Java Interview questions:

Java.lang Package      |       OOPS concepts      |       Access Modifiers






1 comment:

Anil Nivargi said...

Thanks...Here another one blog also explained good please go through this blog http://adnjavainterview.blogspot.in/2014/06/exception-handling-questions.html