Is 1/0 a legal Java expression?

前端 未结 8 1212
萌比男神i
萌比男神i 2020-11-27 16:47

The following compiles fine in my Eclipse:

final int j = 1/0;
// compiles fine!!!
// throws ArithmeticException: / by zero at run-time

Java

8条回答
  •  旧巷少年郎
    2020-11-27 17:23

    Why bother catching this at compile-time, when you're going to need a run-time variant anyway?

    For example, if you were loading and parsing "0" from a text file, then tried to divide by it, Java would have no idea what you were doing at compile-time because it doesn't know the contents of that external file.

    Also if you were to set any variable to 0 and divide by the variable, Java would have to keep track of every possible value of every variable at every point in the script in order to catch a divide by 0 at compile time.

    Might as well keep things consistent and make it a runtime-only exception.

提交回复
热议问题