A gotcha with Try/Catch and ExceptionTypes

A small puzzle of a real-world ‘gotcha’ that got me recently.

What’s wrong with this code?

try
   dim mb as new MemoryBlock(10)
   dim b as Byte = mb.byte(11) // intentionally out of range which will trigger an Out Of Bounds Exception
catch NilObjectException
    MsgBox “Caught NilObject Exception"
end try

I’ve posted the answer as a feature request: feedback://showreport?report_id=53074

You declared a variable, NilObjectException, to catch a generic RuntimeException.

Now let me go look at the case…

I agree with your proposal if limited to only the Catch clause. This very limited change would end up helping developers fix bugs rather than breaking code.

Well, at the very least I could argue that the variable declaration isn’t complete and should throw a compiler error. You could have just as easily written:

try dim mb as new MemoryBlock(10) dim b as Byte = mb.byte(11) // intentionally out of range which will trigger an Out Of Bounds Exception catch x MsgBox “Caught NilObject Exception" end try

And it would be the same error, just with a different variable. What is x? By default, I guess, it’s a…variant? A RuntimeException? Either way I would expect a non-definition to be a compiler error.

I believe it’s a RuntimeException by default, but you’re right, typing should be required there and the compiler could help “fix” that issue by supplying the type where it’s missing. The code catch NilObjectException would get changed to catch NilObjectException As RuntimeException, make it clear to anyone perusing that method while not breaking any existing code.

as was pointed out in the feedback case, xojo enforces few rules about variable names, so one can write awful code such as

dim Uin32 as Byte
dim Window as Xojo.Core.MemoryBlock
... etc ...

So maybe the feature request should be a little bigger in scope?