1 try catch solution for exception

How to handle run time exception in java program?

Try and catch are two maximum useful keywords in java programs. Using this keywords we can handle run time exception.

In this blog we can handle ArithmeticException using 1 try catch solution.

 

How to handle exception using 1 try catch solution?

import java.util.*;      

class Exc2

{

            public static void main(String args[])

            {

                        Scanner in1 = new Scanner(System.in);

 

                        System.out.print(“Enter X : “);

                        int x = in1.nextInt();

                        System.out.print(“Enter Y : “);

                        int y = in1.nextInt();

 

                        // How to handle Exception

                        // We use try and catch

                        try

                        {

                                    int div = x/y; // divided by zero :-> infinity

                                    System.out.println(“Div = ” + div);

                        }

                        catch(Exception ex)

                        {

                                    //System.out.println(ex); // Run time simple message

 

                                    // Change in Simple User friendly Message

                                    System.out.println(“Please do not insert 0 in Y”);

                        }          

 

                        // Simple display 5 name in o/p screen

                        String name[] = {“Rakesh”,”Rohan”,”Binny”,”Sonal”,”Nilay”};

                        for(String str : name)

                        {

                                    System.out.println(str);

                        }

            }

}

Output:

Output -1

Enter X: 23

Enter Y: 12

Div = 1

Rakesh

Rohan

Binny

Sonal

Nilay

 

Output -2

Enter X: 45

Enter Y: 0

java.lang.ArithmeticException: / by zero

Rakesh

Rohan

Binny

Sonal

Nilay

 

So this is basic example run time exception. Here I mention 2 output of this program.

1st output is perfect program, so when other user put perfect number of x and y variable then got perfect answer of this program.

2nd output is error program, so when other user put 0 value into y variable, program generates ArithmeticException error. Using of try catch solution we can handle the program.

 

Video available on YouTube now.


[sbscrbr_form]

If you have query about this blog, you can directly post comment or subscribe on website.


 

Earn money online

Share and Enjoy

  • Facebook
  • Twitter
  • Delicious
  • LinkedIn
  • StumbleUpon
  • Add to favorites
  • Email
  • RSS

83total visits,2visits today


mayank

Hello, I am Maddy a Java blogger, trainer and developer

Related articles

Leave a Reply

EmailEmail
PrintPrint