range(): optimize func and add error handler