Acknowledged

Incorrect "maybe uninitialized" error

Given this code:

        var x;
        try {
            x = 1;
            throw new Exception();
        } catch (ex) {
            x++;
        }

I get:

ERROR: <device>: bug.mc:6: Value may not be initialized.
ERROR: <device>: bug.mc:6: Cannot perform operation 'add' on types 'Uninitialized' and '$.Toybox.Lang.Number'.

But there is no way to get to the catch block without initializing the variable.

  • when I run something similar in a Java world it returns the same error

    My initial reaction was surprise that something as mature as the java compiler would get this wrong. But as I understand it (and I really don't know java at all) java supports asynchronous exceptions, so literally anything can throw. So it really is possible that it throws after entering the try, but before assigning one to i.

    That's not the case in monkeyc (or if it is, it needs documenting prominently). The only thing that could possibly go wrong would be an out of memory error. But thats not an exception in monkeyc, and you can't catch it.

  • I'm in flux about this. On Perl I get what you (OP) expects, when I run something similar in a Java world it returns the same error:

    www.tutorialspoint.com/compile_java_online.php

    /* Online Java Compiler and Editor */
    public class HelloWorld{
    
         public static void main(String []args){
            int i;
            try {
                i = 1;
                throw new ArithmeticException("bug or not?");
             }
             catch(Exception e) {
                 i++;
             }
         }
    }

    I can see both sides of the coin. If you touch a file before the exception the file gets touched, if you add a DB record and the transaction is commited before the exception it gets stored.

  • This is not true. I mean for sure there's no way the compiler could "know" it,

    Sorry, but you're wrong. The *only* way into that catch block is if something in the try block throws. "x = 1;" cannot throw, and the compiler can, and should know that.

    Or at least, if it doesn't know enough about control and data flow to know that, it shouldn't be issuing this error in the first place...

    Its also bizarre that the compiler issues an error, when it simply can't tell whether its initialized or not. I mean, if it *knows* its not initialized, its fine for it to be an error. If it just thinks that maybe it might not be, but it's not sure, it should at best be a warning (or an error that can be disabled by the user).

  • This is not true. I mean for sure there's no way the compiler could "know" it, and it is possible you think that there can't be any problem before you gave a value to x but maybe there are some ways.