Monday, 22 June 2015

Exceptions?

Throwable
Error  Exception
           (checked)   runtime
                                    (unchecked)
                                                    
Difference between error and exception
Error such as OutOfMemory Error which no programmer can guess and can handle it. It depends on dynamically based on architecture, OS and server configuration. Whereas Exception, programmer can handle it and can avoid application's misbehavior. For example if your code is looking for a file which is not available then IOException is thrown.

Difference between checked and unchecked exceptions? Examples?

Checked                                      Unchecked
Subclass of Excepion                    Subclass of RuntimeException
Known that possibility of             Unchecked can be of logical problems in the code.
Exception will be thrown
Ex: SQL Excepiton
IOException
Clonenot supportedException              Ex : Nullpointer exception,AIOBE,ArithmeticE
Errors                                     
Virtualmachine Error
Outofmemory  Error
StaticOverflow Error
We have to use some access specifier in the subclass which has same or greater access than the superclass method specifies, reverse is the case for exceptions.

Ex:
Class A{
Void m1() throws RuntiemException;
}
Class B extends A
{
}
Valid
---------
Void m1(){ }
Protected void m1() throws Runtime Exception { }
Public void m1() throws AIOBE{}
Invalid
-------
Private void m1() throws Exception{}

Difference between throw and throws?

Throw is used to throw an exception manually where as throws is used in the case of checked exceptions to re-intimate the compiler that we have handled the exception. So throws is to be used at the time of defining a method and also at the time of calling that function which raises a checked exception.
Difference between final, finally and finalize methods?

Final-  is a keyword used to declare constants
Finally()-The finally block always executes when the try block exits, except
  1. System.exit(0) call.
  2. Runtime.exit(int)
Finalize() -method helps in garbage collection. A method that is invoked before an object is discarded by the garbage collector, allowing it to clean up its state
System.exit(0)
Terminates the currently running Java Virtual Machine. The argument serves as a status code; by convention, a nonzero status code indicates abnormal termination.
This method calls the exit method in class Runtime. This method never returns normally.
The call System.exit(n) is effectively equivalent to the call:
 Runtime.getRuntime().exit(n)

What does finally block does ?

There are 4 potential scenarios here:
1.         The try block runs to the end, and no exception is thrown.  In this scenario, the finally block will be executed after the try block.
2.         An exception is thrown in the try block, which is then caught in one of the catch blocks.  In this scenario, the finally block will execute right after the catch block executes.
3.         An exception is thrown in the try block and there's no matching catch block in the method that can catch the exception.  In this scenario, the call to the method ends, and the exception object   is thrown to the enclosing method - as in the method in which the   try-catch-finally blocks reside.  But, before the method ends, the finally block is executed.
4.  Before the try block runs to completion it returns to wherever the method was invoked.  But, before it returns to the invoking method, the code in the finally block is still executed.  So, remember that the code in the finally block will still be executed even if there is a return statement somewhere in the try block.
In Java, will the code in the finally block be called and run after a return statement is executed?
The code in a finally block will take precedence over the return statement.

For Example:

Code that shows finally runs after return
class SomeClass
{
    public static void main(String args[])
    {
        // call the proveIt method and print the return value
            System.out.println(SomeClass.proveIt());
    }
    public static int proveIt()
    {
            try { 
                        return 1; 
            } 
            finally { 
                System.out.println("finally block is run
            before method returns.");
            }
    }
}

Running the code above gives us this output:
finally block is run before method returns.
1

Very unique situations when finally will not run after return

The finally block will not be called after return in a couple of unique scenarios: if System.exit() is called first, or if the JVM crashes.
What if there is a return statement in the finally block as well?
If you have a return statement in both the finally block and the try block, then you could be in for a surprise. Anything that is returned in the finally block will actually override any exception or returned value that is inside the try/catch block. Here is an example that will help clarify what we are talking about:
public static int getANumber(){
    try{
        return 7;
    } finally {
        return 43;
    }
}
The code above will actually return the “43″ instead of the “7″, because the return value in the finally block (“43″) will override the return value in the try block (“7″).
Also, if the finally block returns a value, it will override any exception thrown in the try/catch block. Here is an example:
public static int getANumber(){
    try{
        throw new NoSuchFieldException();
    } finally {
        return 43;
    }
}
A return statement in the finally block is a bad idea.....
Running the method above will return a “43″ and the exception in the try block will not be thrown. This is why it is considered to be a very bad idea to have a return statement inside the finally block.

 




No comments:

Post a Comment