Home > Enterprise >  Catch NumberFormatException has different behaviour?
Catch NumberFormatException has different behaviour?

Time:05-19

I was writing a code to show examples of try/catch and I notice that the same catch NumberFormatException was triggered or not depending on where I use it. This is the code:

public class Main {
public static void main(String[] args) {

    System.out.println("3/0 => Result: "   divide(3,0));  // returns 3/0 => Result: null
    System.out.println("6/2 => Result: "   divide(6,2));  // returns 3/0 => Result: 3
//        System.out.println("6/home => Result: "   divide(Integer.parseInt("home"),1));

    try {
        System.out.println("6/home => Result: "   divide(Integer.parseInt("home"),1));
    } catch (NumberFormatException e) {
        System.out.println("Error type: NumberFormatException (MAIN METHOD)");
    }
}

static Integer divide(int n1, int n2) {   // we used Integer (wrapper class) to be able to return null

    int result = 0;

    try {
        result = n1 / n2;
    } catch (ArithmeticException e) {
        System.out.println("Error type: ArithmeticException");
        return null;
    } catch (NumberFormatException e) {
        System.out.println("Error type: NumberFormatException");
        return null;
    }
    return result;
}
}

The code returns:

Error type: ArithmeticException
3/0 => Result: null
6/2 => Result: 3
Error type: NumberFormatException (MAIN METHOD)

But if I enable the 3rd line:

System.out.println("6/home => Result: "   divide(Integer.parseInt("home"),1));

And disable the try/catch inside main method the NumberFormatException inside the divide method does not trigger and it crash the program.

Can anyone explain why? I am using the same exception type, why it works inside the main method but it does not work inside the divide method?

CodePudding user response:

Catching exceptions is depending on the exception happening inside the corresponsing try{} block. By disabling the try / catch inside the main method the occuring number format exception is not in any try{} block anymore and therefore "crashes" your program. The try / catch inside the divide method is in that case never even reached, as the exception happens while the thread is executing the code 'Integer.parseInt("home")' which is outisde of that block / inside your main method.

CodePudding user response:

It's because the Integer.parseInt method is called from the main method and not inside try / catch block. Look at the stack trace that should be printed out.

Exception in thread "main" java.lang.NumberFormatException: For input string: "home"
    at java.lang.NumberFormatException.forInputString(NumberFormatException.java:65)
    at java.lang.Integer.parseInt(Integer.java:580)
    at java.lang.Integer.parseInt(Integer.java:615)
    at Main.main(Main.java:6)

The last line (Main.main(Main.java:6)) is giving you a clear hint from where the exception was thrown out in your code.

  • Related