Exception Handling



Program to implement Exception Handling

import java.io.*;
public class ExceptionHandling {
    public static void main(String[] args) throws IOException {
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
        System.out.print("Enter Integer Number:: ");
        String s = br.readLine();
        int n, i, f = 1;
        try {
            n = Integer.parseInt(s);
            for (i = 1; i <= n; i++)
              f = f * i;
            System.out.println("\nFactorial of " + n + " is:: " + f);
        } catch (NumberFormatException e) {
            System.out.println("\nERROR!! Only integer value allowed");
        }
    }
}


OUTPUT::


Enter Integer Number:: 5.5

ERROR!! Only integer value allowed

NOTE:
Here, I have entered 5.5 as input, as it is not an integer it will throw NumberFormatException, which is caught by catch block and the statement in catch block will be executed.


Previous Post Next Post