Saturday 1 September 2012

Using try, catch and finally in JAVA

Hi Friends. This post is just to show the effectiveness of using EXCEPTION HANDLING in any programming language. Well I thought about bringing my ideas regarding the matter taking JAVA as the base code which is my favourite. In Java, Exception is used in the form of a class with various Sub classes. It follows an Hierarchy of parent and child class which basically Throwable as the base and the Exception and Error are sub. For Details click here and here.




When i came across the idea of using Exception Handling in C. I always wondered why can't we use simple if else for checking Errors.........


Now consider a simple program as an example.......







In the above program, Inside loop3....The code  " a = a/k; " performs division operation and stores the result in variable 'a'.............
The following program would print the following Exceptional Error message as Output if value of 'k' is 0......

"Exception in thread "main" java.lang.ArithmeticException: / by zero"

i.e the above message tells that the following is a Divide by Zero Exception.........

Now, Here we can simply use an if condition to break from the loop.........

if(a==0)
{
         break;
}

or

if(a==0)
{
         a++;
         continue;
}

Now As we can see, We just introduced break for the innermost loop and so it thereby breaks from the innermost loop.....But, What about breaking from the three loops completely in this particular Exceptional case instead of just coming out from the innermost loop. Well, If you are still in love with the traditional if-else strategy, then have fun with your own logic of escaping from the three loops (probably using a variable for detecting/ storing the loop no being iterated).


Now in the following code, whenever you find a Divide by Zero Exception or any other Arithmetic Exception....The execution directly jumps to its corresponding Arithmetic Exception......................
So..In use terms, Exception Handling is nothing but just the flow of control of execution within a program..

To get a basic diagramatic flow of Exception Handling ........

 
The other way you can control the flow is somewhat like this......

 



Sometimes, for certain situation, there's no other way that using Exception handlers...

Now in a situation like this.....

public class cast_exec 
{
    private static int number;
    private static String name;
    public static void main(String Data[])
    {
        try

        {
            name = "Arjun";
            number = Integer.parseInt(name);
        }
        catch(NumberFormatException e)
        {
            System.out.print("\n\n Received Cast Exception");
        }
    }
}

You can completely forget about using an if - else statement if you are a pure beginner at JAVA if you wanna handle these sort of codes........

You can use keyword throws for throwing Exception out of a function.
for e.g:

public int divide_num(float a, float b) throws ArithmeticException
{
        float res = a/b;
        return res;
}


public static void main(String Data[])
{
        float num1,num2;
        num1 = 0.0;
        num2 = 10.0;
        try
        {
                  num1 = divide_num(num1,num2);
         }
         catch(ArithmeticException e)
         {
                  System.out.print("\n\n\n Exception Caught :   "+e.getMessage());
         }
}

Using Finally along with try-catch

Now, to give an advantage of finally in try - catch statements.......

Consider a program where following occurs......

public static void main(String Data[])
{
          try
          {
               // Includes code for connection with mysql server................
              // Performs mysql operation using java jdbc driver or any other........
              // Closing the Connection with the Server (Compulsory)..........................
           }
           catch(SQLException e)
           {
                    System.out.print("\n\n\n SQL Exception Occured :   "+e.getMessage());
           }
}

Here, SQL Exception involves updation or selection Error based on database contents or SQL syntax etc.....

As usual scenarios, due to certain SQL Exception, the control is thrown to the catch section as normal. But it lefts the connection open and may cause serious problems while connecting many clients to SQL Server (especially Connection pooling). So we need to close the  connection even if the Exception occurs or not... So thereby we include a particular section called finally where we include codes to executed independent of the occurence of Exception........
            
public static void main(String Data[])
{
          try
          {
               // Includes code for connection with mysql server................
              // Performs mysql operation using java jdbc driver or any other........
           }
           catch(SQLException e)
           {
                    System.out.print("\n\n\n SQL Exception Occured :   "+e.getMessage());
           }
           finally
           {
                   // Closing Connection................(code works independent of the occurence of the Exception) .........
           }
}

So i hope u guys really understood the benefits of using Exception Handling over traditional control structures from certain view point...and it easyness to handle error and Exceptions within a programming code Execution....
Well...thanks to go through this patiently and of course this is my first Blog ....Please sorry for any mistakes...if did commited any(there gotta be many).......c ya.....