How to manage errors in DOS with the exit code (known as the Errorlevel) ?

About

This article shows you how to manage error handling with the exit code of DOS.

In dos: When the errorlevel is:

  • = 0, then No Error occurred
  • > 0, then an error occurred

How to

Check the exit status of the previous command

You can test if with the if errorlevel statement:

  • If error is greater than 1
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:

  • bat files use one % to define a variable (By using 2 %, you will get then an error)
@echo off
for %%v in (*.bat) do echo %v
  • Running it cause this errors to occur:
error.bat
v was unexpected at this time
  • When you check the value of the ERRORLEVEL, you get:
echo %ERRORLEVEL%
9009
if errorlevel 9009 (echo bad variable initialization) else (echo that's all good)
bad variable initialization
  • But the default operator is not an equality but a “greater than”, then this “if” statement will also work
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

exit a script from a subroutine ?

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

(reinitialize|reset) it

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

End the script properly

Before the end of the script

if %ERRORLEVEL% neq 0 (
  exit /b %ERRORLEVEL%
)

where:


Powered by ComboStrap