Because System.requestVersion
(see @sfdcfox's answer) throws an uncatchable exception on a scratch org for package development, you cannot use this code on that scratch org and any unit tests covering such code will fail. See this idea for details.
The documentation for Version
actually states (up to apex API version 55 at least):
The value returned by the System.requestVersion method is an instance of this class with a two-part version number containing a major and a minor number. Since the System.requestVersion method doesn’t return a patch number, the patch number in the returned Version object is null.
Since System.requestVersion().patch()
is thus always null, you may want to just do a namespace prefix query like this:
SELECT MajorVersion, MinorVersion
FROM Publisher
WHERE NamespacePrefix = 'namespace'
ORDER BY MajorVersion DESC, MinorVersion DESC
LIMIT 1
The reason for the ORDER BY
is that sometimes Salesforce reports both a (0, 0) version and an (x, y) version when it should only report the latter.
It is also worth noting that System.requestVersion
is not compatible with 2GP managed packages, as covered here.
In the scratch org this will return 0 and 0, but at least that is better than suffering from an exception and having to do special case code to avoid uncatchable exceptions as covered in this other Q&A.
For the specific handling for a post-install page, where you want to guarantee having the patch version, I would suggest you update your installer to save the version it is given in a protected custom setting or custom metadata type record so you have full detail.