Search code examples
javaexceptionruntimenan

Java : Is 'Square root of a negative number' a logical error or a runtime error?


I was solving a practice examination paper, and it had the question - Which of the following errors will the snippet produce ? -

System.out.println(Math.sqrt(24-25));

Logical, Runtime, Syntax

I know it will give NaN, but can someone confirm what type it will be included in? Thank you.


Solution

  • Which of the following errors will the snippet produce -

     System.out.println(Math.sqrt(24-25)); 
    

    Logical, Runtime, Syntax.

    This won't produce a syntax error or any other kind of compilation error1.

    This won't produce a runtime error in the sense that that term is used in Java; i.e. no exception will be thrown. The sqrt call terminates normally and returns a NaN value. NaN is a well-defined value, per the Java Language spec and IEE floating point spec.

    Is it a logical error? That depends on the specification of your program. But on the face of it, outputting "NaN" as the square root of -1 is a reasonable thing to do.

    So, in the absence of a specification, I would be inclined to say that there is no error here at all.

    However, in other contexts using a NaN generated by sqrt could be a logical error, and could indirectly give rise to runtime errors (in the Java sense).

    The lesson is that it is not possible to classify errors without considering the context. Even the meaning of the types of errors is context dependent2.


    1 - ... unless you shadow the standard java.lang.Math class.
    2 - For instance, it depends on the precise definitions of "Logical error", "Runtime error", "Syntax error" and so on that you have been taught. Or the programming language you are using.