You have to set it by using System.Exit(value)
when you end your application. So a way would be to control your exceptions which make the program to finish abnormally, and then end the program using it to return the value you want for the errorlevel
.
You can return the int
value you want using it. As example:
// If I had IOException, then
System.exit(3);
Reference: System.exit
Edit: the problem you have about the number comes with the %errorlevel%
value, use ERRORLEVEL
instead, like:
if ERRORLEVEL 0 (
echo All ok
) else (
echo An error
)
Just notice that ERRORLEVEL compares if %errorlevel%
has a value equal or higher than the one you're giving to it.
Why do I say this? I've experienced the same problems than you before, that %errorlevel%
seems to update later than when it must. I don't know the reason, but i can tell you that if you check it's value by ERRORLEVEL
, you would check that this value is the correct one.
You only have to check your higher values returned before, since ERRORLEVEL
checks if the value is equal or higher.
Reference: %errorlevel% is not ERRORLEVEL