Peter N Lewis wrote:
Does New as a function return nil or does it still give a runtime error?
If I want to allocate memory, but handle it gracefully if it fails, what are the recommended approaches?
You could also trap runtime errors, using `AtExit', or use the `Trap' unit (which does this internally). This comes somewhat closer to exception, though it's not quite the same. Indeed, this may be the best solution available. It's a bit code to write, but it uses `New' and has no disadvantages in this regard.
Ok, it's an interesting approach, but I'd have to write that code for each type, which is still pretty ugly.
I just checked, and if New returns nil (using the UndocumentedReturnNil for example), the compiler will blindly try to Initialize the returned data, and bus error.
I'm not sure if this counts as a bug, since presumably UndocumentedReturnNil is only suppose to be for BP compatibility, and with BP compatibility there would be no Schema and thus no initialization. Unless perhaps BP has objects, in which case, New(obj) which returned UndocumentedReturnNil would probably have the same bus error issue.
It's a shame, as this would be the best solution (documenting UndocumentedReturnNil and allowing GetMem to return it).
I'd love to start using New and Schema and such, but the best solution seems to be the Trap technique and that's some ugly code to have any place you want to use New and not crash out.
I guess I can stick to using the system NewPtr routine and manually calling Initialize, but that doesn't mesh will with Schema.
I did think of another hack, which was to pre-allocate a chunk of memory larger than the largest New command, and then have GetMem return that for failure, then rather than testing for nil, I could test of that safe return value. It's ugly, but probably the simplest solution that provides clean New code. Peter.