This article shows you how to manage error handling with the exit code of DOS.
In dos: When the errorlevel is:
You can test if with the if errorlevel statement:
if ERRORLEVEL 1 (
echo an error occurred
exit /B %ERRORLEVEL%
)
if %ERRORLEVEL% neq 0 (
echo an error occurred
)
REM or
if %ERRORLEVEL% equ 0 (
echo no error occurred
)
Below is a more detailed example:
@echo off
for %%v in (*.bat) do echo %v
error.bat
v was unexpected at this time
echo %ERRORLEVEL%
9009
if errorlevel 9009 (echo bad variable initialization) else (echo that's all good)
bad variable initialization
if errorlevel 9000 (echo a bad thing occurs) else (echo that's all good)
a bad thing occurs
if %errorlevel% EQU 9009 (echo the error 9009 occurs) else (echo the error 9009 doesn't occurs)
the error 9009 occurs
In a function or subroutine, the command exit /b exits only the subroutine and not the script. You need to exit the subroutine with a goto and call the exit command
(goto) 2>nul || exit /b %ERRORLEVEL%
Example of function that can be called to check the previous command execution.
:checkErrorLevel
if ERRORLEVEL 1 (
echo "An error occurred"
REM exit the subroutine then exit the script
(goto) 2>nul || exit /b %ERRORLEVEL%
) ELSE (
echo "The previous command has executed successfully"
)
goto :eof
To reinitialize it to 0 after an error, you use the exit command with the B switch in a child batch script:
For instance, with the following script named: resetErrorLevel.bat
:: This script is there just to reset the error level
exit /B 0
If you start this demo script:
@echo off
echo Before the error, the errorlevel value is: %ERRORLEVEL%
copy badfile badlocation
echo After the error, the errorlevel value is: %ERRORLEVEL%
call resetErrorLevel.bat
echo After the resetErrorLevel.bat, the errorlevel value is %ERRORLEVEL%
you will get this output:
Before the error, the errorlevel value is: 0
The system cannot find the file specified.
After the error, the errorlevel value is: 1
After the resetErrorLevel.bat, the errorlevel value is 0
Before the end of the script
if %ERRORLEVEL% neq 0 (
exit /b %ERRORLEVEL%
)
where: