Tuesday, June 27, 2017

What happen when you are not print or throw the exception in catch block?

try block-- Here the actual logic and implementation. 
catch block--If try block may have come error in the logic or implementation we can catch the error.Here we can catch the try block error.Catching error is just do print the stack trace of the what error is occurred.

Now consider we are trying below condition, its just do create exception in try block,do not bother about implementation in try block.

package com.test.java;

import java.util.Scanner;

/**
 * @author boomiraj
 *
 */
public class Test {

    /**
     * @param args
     */
    public static void main(String[] args) {
        Scanner l_objInput = new Scanner(System.in);
        System.out.println("Please Enter the value : ");
        convertStringToInt(l_objInput.next());
    }

    private static void convertStringToInt(String p_sValue) {
        int i = 0;
        try {

            i = Integer.parseInt(p_sValue);
            if (i < 100) {
                i = i + 1;
            } else {
                i = i - 1;
            }

        } catch (NumberFormatException e) {
         }
        System.out.println("Converted into interger from string : " + i);
    }

}


In public method we are calling convertStringToInt(String) to convert given String Value to Int.
   
    We are getting input from user, so user can enter any possible combination of input like
    Alphabet
    Alphanumeric
    Number
    Special character
   
    If user enters only Number, its not problem we can get the output without error.
    But if he tries any other combination then there is possibility to have an error.
    In this scenario we are catch the exception, but in the catch block we don't have any print stack trace or print log.
    then the user does not know that the entered values are not able to convert into Int. But he always get some output.

    This may cause the some blocker issue in your project.

  catch (NumberFormatException e) {
            System.err.println("Cannot convert the value '" + p_sValue
                    + "' to integer");
        }


So always print something into your catch block.

1 comment:

  1. Baccarat - The Ultimate Guide to Playing Online | The
    Baccarat is one of the 바카라 사이트 most popular casino games. It deccasino can be played for the thrill of winning, and many players enjoy it on 1xbet korean the go. Baccarat is one of

    ReplyDelete