wrong variant order can cause exception
Imported from https://youtrack.roxen.com/issue/PIKE-11
Reported by KG Sterneberg kg@roxen.com
Running the following code:
int main(int argc, array(string) argv)
{
array exceptions = ({
Error.mkerror("Ett vanligt fel..."),
MyException("Oh no! Something blew up."),
MyError("This is my error"),
"hej hopp gallop",
});
foreach (exceptions, mixed obj) {
handle_error(obj);
}
return 0;
}
variant void handle_error(mixed e) {
werror("Handle an error of unknown type: %O\n", e);
}
variant void handle_error(MyException e) {
werror("Handle an MyException: %s\n", describe_error(e));
}
variant void handle_error(Error.Generic e) {
werror("Handle an Error.Generic: %s\n", describe_error(e));
}
variant void handle_error(MyError e) {
werror("Handle an MyError: %s\n", describe_error(e));
}
class MyException {
inherit Error.Generic;
protected void create(string message) {
::create(message, backtrace());
}
public constant is_my_exception = true;
}
class MyError {
inherit Error.Generic;
protected void create(string message) {
::create(message, backtrace());
}
public constant is_my_error = true;
}
results in:
>pike exception-test.pike
*Calling undefined function.*
exception-test.pike:27: /main()->handle_error(_static_modules.Builtin()->GenericError("Ett vanligt fel..."))
exception-test.pike:15: /main()->handle_error()
exception-test.pike:10: /main()->main(1,({"/Users/kg/dev/learning/pike/exception-test.pike"}))
Just by switching the order of the handle_error variants lite this:
variant void handle_error(mixed e) {
werror("Handle an error of unknown type: %O\n", e);
}
variant void handle_error(MyException e) {
werror("Handle an MyException: %s\n", describe_error(e));
}
variant void handle_error(MyError e) {
werror("Handle an MyError: %s\n", describe_error(e));
}
variant void handle_error(Error.Generic e) {
werror("Handle an Error.Generic: %s\n", describe_error(e));
}
will make the program work:
>pike exception-test.pike
Handle an Error.Generic: Ett vanligt fel...
Handle an MyException: Oh no! Something blew up.
Handle an MyError: This is my error
Handle an error of unknown type: "hej hopp gallop"
This behaviour is dangerous and a potential source of bugs that can be hard do discover.
P.S. Moving the deklarations of MyException and MyError above the main-function also solves the problem.