Thursday, 26 December 2013

Expect the EXPECTION and handle it !!

Its always better to handle an exception in java program.Exception will interrupt the program flow and affect robustness of program.Once exception occurs it will stop the further execution. So better handle exception and dont scared users by not handling exceptions:p Please go through below for exceptions and also refer other sites too.

What is an Exception?
*************************
It’s a non functional requirement for any application, to gracefully handle any erroneous condition like resource not available, invalid input, null input, index not available and so on.Java Exception are divided into two categories as checked Exception and unchecked exception.
Checked Exception: Exception that can be identified during compile time. Basically Exception will throw compilation error.
UnChecked Exception: Exception which can't be predicted during compile time is unchecked exception. Unchecked exception is the exception which will occur during runtime.
Unchecked Exceptions mostly arise due to programming errors like accessing method of a null object, accessing element outside an array bonding or invoking method with illegal arguments. Unchecked exceptions are the direct subclass of RuntimeException.
Errors:Errors are serious runtime environment problems that are almost certainly not recoverable. Some examples are OutOfMemoryError, LinkageError, and StackOverflowError. They generally crash you program or part of program. Only a good logging practice will help you in determining the exact causes of errors.

Implementation of Exception:
******************************
Checked exceptions can be handled by throws keyword. Throws will be declared on the method. Throws will not be used inside of any method. Checked exceptions such as IOException, Sql Exception can be throwed by throws. Throws can be able to throw more than one exception at a time using comma operator. syntax are as folows.
---------------------------------------------------------------------------------------
public static void main(String[] args) throws IOException,SQLException{
// body of function
}
---------------------------------------------------------------------------------------

Unchecked exceptions can be handle by try catch block. Block of code which may throw exceptions during runtime will be declared inside try block.Try block could state that code which is there inside of me may or may not throw exception. If its standard exception such as Nullpointer exception, Indexoutofexception etc then compiler will throw an exception. If its custom exception then programmer has to throw that exception explicitly.For Example, you want to throw an exception of below age if age is less than 18.This is custom exception and not standard exception.

-------------------------------------------------------------
public void method1()
{
String[] firstName= new firstName[2] ;
int age;
// getting input of age and first name here
try{
if(age is < 18)
{
throw new outOfAgeException("Below age");
}
System.Out.println(firstName[2]);
} System.out.println(null);
}
-------------------------------------------------------------
In the above example custom exception is "below age" and standard exception is " IndexoutofException". Exception will be handled for the codes is there inside the try block.So null pointer will not be able handle but it will be thrown. Catch block will be used for handling an exceptions. More than one catch block can also be declared. If you are declaring more than one catch block for handling an exceptions then it should be in an order of specific to generic. Suppose you are declaring catch for Arrayindexoutofexception and exception. Then catch block with arrayindexbound should come first and catch block with General exception should come next.Lets see what will happen if we declared general exception first. If we declare catch block with general exception first, then all exceptions will be caught by catch block with general exception. Even arrayindexbound exception will also be caught by catch block with general exception and it cant be catch by catch block with arrayindexbound exception. Here is an Example.
------------------------------------------------
catch(arrayindexboundException arr)
{ LOGGER.error("Checkout your array index", arr);
} catch(Exception e)
{
LOGGER.error("Some information", e);
}
------------------------------------------------

Stacktrace: Stackrace is use to find root cause of an exception. Once function is called its reference will be saved in stack. If that function throws any exception then pointer of stack will go back to find the root cause of an exception.Mainly stacktrace will be useful debugging and tracing your code.

Tips for handling an Exception:
*****************************************
1) Always use Finally block if you are handling an exception. There some situations where we need to close database connection, file connection etc. Such statements can be written in finally block. Once exception is occurred, your application will be stopped abtruptly but statements which has been declared inside finally block will be executed.Code inside the finally block will be executed though exceptions are thrown or not.Always clean up after handling the exception.
2)In catch block don't do return null. In that case, exception could be swallowed and stacktrace couldn't find root cause.

-----------------------------------------
catch (NoSuchMethodException e) {
return null;
}
-----------------------------------------

3) use always standard exception so that other programmers can also understand about that exception. If you are using custom exceptions then document all exceptions in your application in javadoc
4) Don't throw any exceptions from finally block.
5)Validate user input to catch adverse conditions very early in request processing.
6)Always include all information about an exception in single log message.
-----------------------------------------
LOGGER.debug(“Using cache sector A”);
LOGGER.debug(“Using retry sector B”);
-----------------------------------------
Don’t do this.

Happy Learning !!



Monday, 23 December 2013

Show Encapsulation by hiding data!!

One of the most important feature in Java is Encapsulation. Here I am going to brief about encapsulation.Hope it will be useful for you.Don't come into the conclusion only with this blog.Dig other site also to get more information about encapsulation.

There will be some situations where we required to show only some information not all.How can we implement that ? For example,Its enough to show overall attendance percentage to students. But when it comes faculty, all details need to be displayed.Here students will be the class and Faculty will be the class. Attendance here is the data. What we are doing here is we are protecting and hiding data from student class.How can we acheive this? The solution for this question is Encapsulation. Encapsulation is about to protect the data(varaibles), information(methods) etc.By using access modifiers such as public, protect, default and private we can implement encapsulation.

Encapsulation is also for protect information which are prone to change. Encapsulation is used to maintain code just in one place. not scattered around code is easy to change.This can be better explained with an example.There a class called loan and it has a parametrized constructor.Other class have an instance using this constructor. Now requirements have changed to add another parameter in constructor. So you need to change everywhere you are calling this constructor. This is what code is scattered and encapsulation can handle it by access specifier.

Example of Encapsulation in Java
*********************************
class Loan{
private int duration; //private variables examples of encapsulation
private String loan;
private String borrower;
private String salary;

//public constructor can break encapsulation instead use factory method
private Loan(int duration, String loan, String borrower, String salary){
this.duration = duration;
this.loan = loan;
this.borrower = borrower;
this.salary = salary;
}

//no argument consustructor omitted here

// create loan can encapsulate loan creation logic
public Loan createLoan(String loanType){

//processing based on loan type and than returning loan object
return loan;
}

}