Try- Catch block

In some programming languages , when a problem occurs during a execution , there is no way for you as a programmer to catch it and deals with the problem . In Java , most problems cause what are known as a exception . 

Java try that a block is used to enclose the code that might throw an exception . No code can be between the end of the try block and the beginning of the catch block . 

When a method states that it will throw an exception , there should be a catch block to catch the particular exception . If there is an error while reading , an exception called as IOException is thrown . When that happens , the code in the catch block is known as . There can be more than one catch block for a single try block . 
Let us see an example given below:-

/*Write a program in Java to find the sum of three numbers entered by the user.*/

import java.io.*;

class sum

{
             public static void main(String[] args)      
      {            InputStreamReader in=  new InputStreamReader    (System.in);
               BufferedReader br=  new BufferedReader(in);
          try
{
       System.out.println("Enter the First number");
       int m = Integer.parseInt(br.readline());
        System.out.println("Enter the second number");
        int n = Integer.parseInt(br.readline());
        System.out.println("Enter the third number");
         int o = Integer.parseInt(br.readline());
        int sum = m+n+o;
         System.out.println("The sum of the three entered numbers are   : "+ sum);

          
}
        catch  (Expression IO)
      {
         System.out.println   ("Unexpected");
      }                          
           } 




Output:-
Enter the first number
23
Enter the second number
56
Enter the third number
89
The sum of the three entered numbers are: 168

Post a Comment

أحدث أقدم