Using Errorlevel to handle program return code

When running a command line program from a batch file, then the program will end with a return code, which usually specifies whether the program succeeded. One can catch the return code and use it in the batch file.

@ECHO OFF
DB2 CONNECT TO MY_DB
IF ERRORLEVEL 1 GOTO ERROR
IF ERRORLEVEL 0 GOTO SUCCESS

:SUCCESS
ECHO SUCCESS
GOTO EXIT

:ERROR
ECHO ERROR
GOTO EXIT

:EXIT

Note one should always check the highest errorlevel first. Because the errorlevel check is less or equal. So if a program returns 15 and one checks if errorlevel==0 then it would return true.

Note one should use GOTO when doing errorlevel checking. Because if not, then it will continue to check the errorlevels below the one it matches.

Related Access selection from CHOICE using ERRORLEVEL

More Info MS KB69576

Note one can also pipe the different types of errorlevel codes to a file:

DB2 CONNECT TO MY_DB 1>>error.txt 2>>error.txt

Updated: 2 July 2007

Leave a Reply

Your email address will not be published. Required fields are marked *