Tuesday, August 12, 2014

Posted by Anmol Sharma
Exception handling in java is similar as in C#. There are couple of differences like java allows checked exceptions which are handled by the caller of the program. Another minor difference is in the finally statement which can have return and break statement which is not the case in C#.

Refer to previous article for Introduction to Exception handling Exception Handling Basics in C#

Following code illustrates the basic concept of exception handling dealing with divide by zero exception in Java. As we know exception is any abnormal condition in a program which abrupt the normal flow of the program. Exception handling allows users to take corrective measures and have easy to understand information returned to them in case an exception arises.


import java.util.*;

public class ExceptionTrial {
               
                public static void main(String[] args){
                Scanner input = new Scanner(System.in); //allows the user to input values
               
                int x=1;
               
                do{
               
                try{ //put the code in try block which may raise an exception
                               
               
                System.out.println("Enter a number  :");
                int n1=input.nextInt();
                System.out.println("Enter another number to divide");
                int n2=input.nextInt();
                int sum = n1/n2;
               
                System.out.println(sum);
                x=2;
                }
               
                catch(Exception e){   //handles the exception, lets the user know whats wrong.
                               
                                System.out.println("You can not divide a number by zero");
                               
                }
                }while(x==1); // loop to let user enter correct value after encountering exception
               
               
                }
            
}

Screenshot // click to open a higher resolution version


0 comments:

Post a Comment