Finally-: finally is a block always associated with try catch to maintain clean-up code.The spaciality of finally block, it will be executed irrespective of whether exception raised or not raised and whether handle or not handled.
Syntax-:
try{
risky code
}catch(Exception e){
throw exception
}
finally{
clean-up activity
}
Final-: final is modifier applicable for classes method and variables.
- If a class declared as final we can't extend that a class that is we can't create child class for that class that is inheritance is not possible for final classes.
- If a method is final, we can't override that method in the child class.
- If a variable declared as final, then we can't perform reassignment for that variable.
Finalize() -: finalize is method always invoked by garbage collector just before destroying an object to perform clean-up activities, once finalize method complete immediately garbage collector destroys the objects.
Note-:
Finally, block is responsible to perform to clean-up activities related to try block that is what ever resources we open as part of try block will be closed inside finally block.
Whereas finalize method is responsible to perform clean-up activities related to object that is what ever resources associated with object will be relocated before destroying an object by using finalize method.
Various possible combination of try catch finally.
- try -catch, finally, order is important.
- When ever writing try compulsory we should write either catch or finally. Otherwise we will get compile time error. That is, try without catch or finally is invalid.
- When ever we are writing catch block, compulsory try block must be required that is catch without try is invalid.
- When ever we are writing finally block compulsory we should write try block that is finally without try is invalid.
- Inside a try catch and finally blocks we can declare try catch and finally blocks. That is nesting are try catch finally is allowed.
- for try catch and finally block curly brace are mandatory.