Monday, April 15, 2013

Java Exception | Exceptions Handling Examples | Try Catch Finally Block



Hi Guys,

I am back with the Latest Topics. What is Exception in Java. Handling Exceptions with Examples.



             In this article, we will see Exception. Exception is very important part of any programming language. Basically, an exception is an abnormal behavior existing during a normal execution of a program. For example: When writing to a file if there does not exist required file then an appropriate exception will be thrown by java code.

Exception

          When an error occurred during the execution of a program, an exception occurs. In other words, exception is a run time error. This may happen because of the occurrence of certain events that arise at the time of execution.

            When an exception occurs, the program terminates unexpectedly and control returns to the operating system(OS). For language that do not support exception handling, programmers have to take care of errors manually. It is important to ensure that the program does not terminate unexpectedly due to the occurrence of an exception.

Handling Exception

            Exception Handling is performed to identify errors and prevent program to stop execution due to errors. Whenever an exception occurs in a program where proper exception handling mechanism is not provided, the program aborts programs stops it's execution.

            Error handling in Java is performed with the help of exception-handling model. According to this model, when an error occurs, an exception is thrown. This exception is caught in block of code. Exception have to be caught, otherwise the program is terminated.

            Exception Handling in Java is managed through five keywords: try, catch, throw, throws and finally.  Program Statements that have to be monitored for exceptions, are contained within try block. By catch keyword, the programmer can catch the exception and handle it. To manually throw an exception, the keyword throw is used. The throws clause is used in a method to specify that this method will throw out an exception. The code in finally block gets executed no matter whether an exception is generated or not.


 'try' and 'catch' Block

Whenever there is a possibility of an exception being generated in a program, it is better to handle it explicitly. This can be done using the try and catch. The advantage of try and catch keywords are that, they fix the error and prevent the program from terminating abruptly.

It is possible to have multiple catch statements for one try block. The execution of a program can continue once the exception has been handled.

For Ex.

try{

            int num = calculate(9,0);

            System.out.println(num);

}catch(Exception ex){

            ex.printStackTrace();

}



int calculate(int a, int b){

            int num = a/b;

            return num;

}

In above example, exception will generate because, number cannot be divided by zero.
Note: The catch block never executed if no error occurs.


The 'finally' block

            'finally' block is placed after catch block, and it is compulsory executes whether catch block execute or not. The code inside finally block will compulsory execute.

For Example, sometimes we don't close connection with database after query get executed. So, in this case, generally we write close connection code in finally. So, possibilities of error generation due to so many connection instance to database, will be reduced.
            'finally' block will only not execute, if programmer calls System.exit(0); in try block.

For Example,

try{

            Connection conn;

            conn = DBConnection();

}catch(Exception ex){

            ex.printStackTrace();

}finally{

            closeConnection();

}


Multiple catch blocks

Sometimes a single piece of code may generate more than one type of error. In such cases this errors should be separated by multiple catch blocks. Each catch statement is seen in order of appearance and the first one that matches the exception is executed. After one of the catch statements is executed, the rest of the catch statements are ignored.

Following example will illustrate, multiple catch() blocks are used to handle different exceptions.

For Example,

class ExceptionCode{

           

            public void calculate(){

                        try{

                                    int num=0;

                                    int num1 = 42/0;

                        }catch(ArithmaticException ae){

                                    ae.printStackTrace();

                        }catch(Exception ex){

                                    ex.printStackTrace();

                        }

            }



            public static void main(String args[]){

                        ExceptionCode obj = new ExceptionCode();

                        obj.calculate();

            }

}

1 comment:

  1. Having read your post, I enjoyed it. Your blog provided very useful information. Your story was a pleasure to read. Touch-typing, otherwise known as finger-typing, involves touching the keyboard as you type. By using all of your fingers at once, muscle memory allows you to find the keys without having to see them. I recommend typing tests for practice. This is a free online tool that measures your typing speed. By using this tool, you can check the speed and accuracy of your typing. Test your typing speed using the WPM profile.

    ReplyDelete