
Every scripting and programming language contains an error handler like Java contains try-catch
for error handling. In a Batch script, there is no direct way to do this, but we can create an error handler in the Batch script using a built-in variable of the Batch script name %ERRORLEVEL%
.
This article will show how we can create a Batch script to handle errors and failures. Also, we are going to some examples that make the topic easier.
Error Handling in Batch Script
When a command successfully executes, it always returns an EXIT CODE
that indicates whether the command successfully executed or failed to execute. So, to create an error handling in a Batch file, we can use that EXIT CODE
in our program.
You can follow below general format to create an error handler:
@Echo off
SomeCommand && (
ECHO Message for Success
) || (
ECHO Message for Failure or Error
)
We can also do that by checking the variable named %ERRORLEVEL%
. If the variable contains a value not equal to 0
, then there might be a problem or error when executing the command. To test the %ERRORLEVEL%
variable, you can follow the below example codes:
@ECHO off
Some Command Here !!!
IF %ERRORLEVEL% NEQ 0 (Echo Error found when running the command &Exit /b 1)
You must note that the keyword NEQ
means Not Equal. And the variable %ERRORLEVEL%
will only contain a non-zero value if there is a problem or error in the code.
An Example That Contains Errors
Below, we shared an example. We will run a Batch file named Your_file.bat
from a location.
We intentionally removed that file from the directory. So it’s an error command.
The code for our example will be:
@echo off
ECHO Running a Batch file
CD G:BATCH
CALL Your_file.bat
IF errorlevel 1 GOTO ERROR
ECHO The file run successfully.
GOTO EOF
:ERROR
ECHO The file didn't run successfully.
CMD /k
EXIT /b 1
:EOF
Now, as the file doesn’t exist in the directory, it will show an error, and you will get the below output when you run the code shared above.
Output:
Running a Batch file
The system cannot find the path specified.
'Your_file.bat' is not recognized as an internal or external command,
operable program or batch file.
The file didn't run successfully.
An Error-Free Code Example That Runs Successfully
In the example above, we made a mistake on the code intentionally to understand how the code works. If we correct it like below:
@echo off
ECHO Running a Batch file
CALL "G:BATCHYourfile.bat"
IF errorlevel 1 GOTO ERROR
ECHO The file runs successfully.
GOTO EOF
:ERROR
ECHO The file didn't run successfully.
CMD /k
EXIT /b 1
:EOF
Then we will get an output like this:
Running a Batch file
This is from the first file
The file runs successfully.
Remember, all commands we discussed here are only for the Windows Command Prompt or CMD environment.
I’m currently writing my first batch file for deploying an asp.net solution.
I’ve been Googling a bit for a general error handling approach and can’t find anything really useful.
Basically if any thing goes wrong I want to stop and print out what went wrong.
Can anyone give me any pointers?
John Saunders
160k26 gold badges247 silver badges397 bronze badges
asked Jul 22, 2009 at 9:15
I generally find the conditional command concatenation operators much more convenient than ERRORLEVEL.
yourCommand && (
echo yourCommand was successful
) || (
echo yourCommand failed
)
There is one complication you should be aware of. The error branch will fire if the last command in the success branch raises an error.
yourCommand && (
someCommandThatMayFail
) || (
echo This will fire if yourCommand or someCommandThatMayFail raises an error
)
The fix is to insert a harmless command that is guaranteed to succeed at the end of the success branch. I like to use (call )
, which does nothing except set the ERRORLEVEL to 0. There is a corollary (call)
that does nothing except set the ERRORLEVEL to 1.
yourCommand && (
someCommandThatMayFail
(call )
) || (
echo This can only fire if yourCommand raises an error
)
See Foolproof way to check for nonzero (error) return code in windows batch file for examples of the intricacies needed when using ERRORLEVEL to detect errors.
answered Jun 13, 2013 at 11:27
dbenhamdbenham
127k28 gold badges249 silver badges385 bronze badges
7
Using ERRORLEVEL when it’s available is the easiest option. However, if you’re calling an external program to perform some task, and it doesn’t return proper codes, you can pipe the output to ‘find’ and check the errorlevel from that.
c:mypathmyexe.exe | find "ERROR" >nul2>nul
if not ERRORLEVEL 1 (
echo. Uh oh, something bad happened
exit /b 1
)
Or to give more info about what happened
c:mypathmyexe.exe 2&1> myexe.log
find "Invalid File" "myexe.log" >nul2>nul && echo.Invalid File error in Myexe.exe && exit /b 1
find "Error 0x12345678" "myexe.log" >nul2>nul && echo.Myexe.exe was unable to contact server x && exit /b 1
answered Aug 27, 2013 at 16:55
1
Other than ERRORLEVEL, batch files have no error handling. You’d want to look at a more powerful scripting language. I’ve been moving code to PowerShell.
The ability to easily use .Net assemblies and methods was one of the major reasons I started with PowerShell. The improved error handling was another. The fact that Microsoft is now requiring all of its server programs (Exchange, SQL Server etc) to be PowerShell drivable was pure icing on the cake.
Right now, it looks like any time invested in learning and using PowerShell will be time well spent.
answered Jul 22, 2009 at 10:52
Brad BruceBrad Bruce
7,6083 gold badges38 silver badges60 bronze badges
3
A successful ping on your local network can be trapped using ERRORLEVEL
.
@ECHO OFF
PING 10.0.0.123
IF ERRORLEVEL 1 GOTO NOT-THERE
ECHO IP ADDRESS EXISTS
PAUSE
EXIT
:NOT-THERE
ECHO IP ADDRESS NOT NOT EXIST
PAUSE
EXIT
answered Jul 9, 2013 at 13:38
Rob DavisRob Davis
611 silver badge1 bronze badge
I guess this feature was added since the OP but for future reference errors that would output in the command window can be redirected to a file independent of the standard output
command 1> file — Write the standard output of command to file
command 2> file — Write the standard error of command to file
answered Feb 6, 2015 at 15:36
Python Unittest, Bat process Error Codes:
if __name__ == "__main__":
test_suite = unittest.TestSuite()
test_suite.addTest(RunTestCases("test_aggregationCount_001"))
runner = unittest.TextTestRunner()
result = runner.run(test_suite)
# result = unittest.TextTestRunner().run(test_suite)
if result.wasSuccessful():
print("############### Test Successful! ###############")
sys.exit(1)
else:
print("############### Test Failed! ###############")
sys.exit()
Bat codes:
@echo off
for /l %%a in (1,1,2) do (
testcase_test.py && (
echo Error found. Waiting here...
pause
) || (
echo This time of test is ok.
)
)
answered Sep 24, 2017 at 7:54
TonnyTonny
212 bronze badges
Its extremely easy!
Create a file that contains:
call <filename> // the file you made
cls
echo An error occured!
<Your commands>
pause
So now when you start it, it will launch your program as normal. But when anything goes wrong it exits and continues the script inside the first file. Now there you can put your own commands in.
answered Nov 17, 2016 at 19:51
BlazeLPBlazeLP
1351 silver badge8 bronze badges
0
ПоделитьсяНашли опечатку?Пожалуйста, сообщите об этом — просто выделите ошибочное слово или фразу и нажмите Shift Enter.
|
Добавить комментарий |
I’m currently writing my first batch file for deploying an asp.net solution.
I’ve been Googling a bit for a general error handling approach and can’t find anything really useful.
Basically if any thing goes wrong I want to stop and print out what went wrong.
Can anyone give me any pointers?
John Saunders
160k26 gold badges247 silver badges397 bronze badges
asked Jul 22, 2009 at 9:15
I generally find the conditional command concatenation operators much more convenient than ERRORLEVEL.
yourCommand && (
echo yourCommand was successful
) || (
echo yourCommand failed
)
There is one complication you should be aware of. The error branch will fire if the last command in the success branch raises an error.
yourCommand && (
someCommandThatMayFail
) || (
echo This will fire if yourCommand or someCommandThatMayFail raises an error
)
The fix is to insert a harmless command that is guaranteed to succeed at the end of the success branch. I like to use (call )
, which does nothing except set the ERRORLEVEL to 0. There is a corollary (call)
that does nothing except set the ERRORLEVEL to 1.
yourCommand && (
someCommandThatMayFail
(call )
) || (
echo This can only fire if yourCommand raises an error
)
See Foolproof way to check for nonzero (error) return code in windows batch file for examples of the intricacies needed when using ERRORLEVEL to detect errors.
answered Jun 13, 2013 at 11:27
dbenhamdbenham
127k28 gold badges249 silver badges385 bronze badges
7
Using ERRORLEVEL when it’s available is the easiest option. However, if you’re calling an external program to perform some task, and it doesn’t return proper codes, you can pipe the output to ‘find’ and check the errorlevel from that.
c:mypathmyexe.exe | find "ERROR" >nul2>nul
if not ERRORLEVEL 1 (
echo. Uh oh, something bad happened
exit /b 1
)
Or to give more info about what happened
c:mypathmyexe.exe 2&1> myexe.log
find "Invalid File" "myexe.log" >nul2>nul && echo.Invalid File error in Myexe.exe && exit /b 1
find "Error 0x12345678" "myexe.log" >nul2>nul && echo.Myexe.exe was unable to contact server x && exit /b 1
answered Aug 27, 2013 at 16:55
1
Other than ERRORLEVEL, batch files have no error handling. You’d want to look at a more powerful scripting language. I’ve been moving code to PowerShell.
The ability to easily use .Net assemblies and methods was one of the major reasons I started with PowerShell. The improved error handling was another. The fact that Microsoft is now requiring all of its server programs (Exchange, SQL Server etc) to be PowerShell drivable was pure icing on the cake.
Right now, it looks like any time invested in learning and using PowerShell will be time well spent.
answered Jul 22, 2009 at 10:52
Brad BruceBrad Bruce
7,6083 gold badges38 silver badges60 bronze badges
3
A successful ping on your local network can be trapped using ERRORLEVEL
.
@ECHO OFF
PING 10.0.0.123
IF ERRORLEVEL 1 GOTO NOT-THERE
ECHO IP ADDRESS EXISTS
PAUSE
EXIT
:NOT-THERE
ECHO IP ADDRESS NOT NOT EXIST
PAUSE
EXIT
answered Jul 9, 2013 at 13:38
Rob DavisRob Davis
611 silver badge1 bronze badge
I guess this feature was added since the OP but for future reference errors that would output in the command window can be redirected to a file independent of the standard output
command 1> file — Write the standard output of command to file
command 2> file — Write the standard error of command to file
answered Feb 6, 2015 at 15:36
Python Unittest, Bat process Error Codes:
if __name__ == "__main__":
test_suite = unittest.TestSuite()
test_suite.addTest(RunTestCases("test_aggregationCount_001"))
runner = unittest.TextTestRunner()
result = runner.run(test_suite)
# result = unittest.TextTestRunner().run(test_suite)
if result.wasSuccessful():
print("############### Test Successful! ###############")
sys.exit(1)
else:
print("############### Test Failed! ###############")
sys.exit()
Bat codes:
@echo off
for /l %%a in (1,1,2) do (
testcase_test.py && (
echo Error found. Waiting here...
pause
) || (
echo This time of test is ok.
)
)
answered Sep 24, 2017 at 7:54
TonnyTonny
212 bronze badges
Its extremely easy!
Create a file that contains:
call <filename> // the file you made
cls
echo An error occured!
<Your commands>
pause
So now when you start it, it will launch your program as normal. But when anything goes wrong it exits and continues the script inside the first file. Now there you can put your own commands in.
answered Nov 17, 2016 at 19:51
BlazeLPBlazeLP
1351 silver badge8 bronze badges
0
The correct name for errorlevels would be return codes.
But since the DOS command to determine the return code is IF ERRORLEVEL
, most people use the name errorlevel.
Errorlevels are not a standard feature of every command.
A certain errorlevel may mean anything the programmer wanted it to.
Most programmers agree that an errorlevel 0 means the command executed successfully, and an errorlevel 1 or higher usually spells trouble.
But there are many exceptions to this general rule.
IF ERRORLEVEL
construction has one strange feature, that can be used to our advantage: it returns TRUE if the return code was equal to or higher than the specified errorlevel.
This means most of the time we only need to check IF ERRORLEVEL 1 ...
and this will return TRUE for every positive, non-zero return code.
Likewise, IF NOT ERRORLEVEL 0 ...
will return TRUE for every negative, non-zero return code.
In CMD.EXE (Windows NT 4 and later) the old-fashioned DOS IF ERRORLEVEL ...
may sometimes fail, since executables may return negative numbers for errorlevels!
However, this can be fixed by using the following code to check for non-zero return codes:
IF %ERRORLEVEL% NEQ 0 ...
Use the code above wherever you would have used IF ERRORLEVEL 1 ...
in the «past».
Thanks for Noe Parenteau for this tip.
In COMMAND.COM (MS-DOS, DOS-box, Windows 9*/ME), to determine the exact return code the previous command returned, we could use a construction like this:
@ECHO OFF IF ERRORLEVEL 1 SET ERRORLEV=1 IF ERRORLEVEL 2 SET ERRORLEV=2 IF ERRORLEVEL 3 SET ERRORLEV=3 IF ERRORLEVEL 4 SET ERRORLEV=4 • • • IF ERRORLEVEL 254 SET ERRORLEV=254 IF ERRORLEVEL 255 SET ERRORLEV=255 ECHO ERRORLEVEL = %ERRORLEV%
This is perfectly OK if we only have to check, say, 15 consecutive errorlevels.
If we need to check every errorlevel, though, there are better alternatives.
(As I learned from Charles Long, in XP the SET command no longer sets an errorlevel itself.)
However, Windows NT 4 and later make it easy by storing the latest errorlevel in the environment variable ERRORLEVEL:
ECHO.%ERRORLEVEL%
will display the errorlevel.
This blog entry by Batcheero explains perfectly why you should never SET the ERRORLEVEL variable.
The safest way to use errorlevels for
all DOS versions is the reverse order check.Start checking the highest errorlevel that can be expected, then check for the one below, etcetera:
IF ERRORLEVEL 255 GOTO Label255
IF ERRORLEVEL 254 GOTO Label254
•
•
•
IF ERRORLEVEL 2 GOTO Label2
IF ERRORLEVEL 1 GOTO Label1
GOTO Label0
:Label255
(commands to be executed at errorlevel 255)
GOTO End
•
•
•
:Label1
(commands to be executed at errorlevel 1)
GOTO End
:Label0
(commands to be executed at errorlevel 0, or no errorlevel)
:End
This will result in many more lines of batch code, but at least it will work in any DOS version.
In Windows NT (Windows NT 4 … Windows 10) this may not suffice, though, because errorlevels can have negative integer values as well.
In DOS (COMMAND.COM), we can use FOR loops to determine the errorlevel:
@ECHO OFF REM Reset variables FOR %%A IN (1 10 100) DO SET ERR%%A= REM Check error level hundredfolds FOR %%A IN (0 1 2) DO IF ERRORLEVEL %%A00 SET ERR100=%%A IF %ERR100%==2 GOTO 200 IF %ERR100%==0 IF NOT "%1"=="/0" SET ERR100= REM Check error level tenfolds FOR %%A IN (0 1 2 3 4 5 6 7 8 9) DO IF ERRORLEVEL %ERR100%%%A0 SET ERR10=%%A IF "%ERR100%"=="" IF %ERR10%==0 SET ERR10= :1 REM Check error level units FOR %%A IN (0 1 2 3 4 5) DO IF ERRORLEVEL %ERR100%%ERR10%%%A SET ERR1=%%A REM Modification necessary for errorlevels 250+ IF NOT ERRORLEVEL 250 FOR %%A IN (6 7 8 9) DO IF ERRORLEVEL %ERR100%%ERR10%%%A SET ERR1=%%A GOTO End :200 REM In case of error levels over 200 both REM tenfolds and units are limited to 5 REM since the highest DOS error level is 255 FOR %%A IN (0 1 2 3 4 5) DO IF ERRORLEVEL 2%%A0 SET ERR10=%%A IF ERR10==5 FOR %%A IN (0 1 2 3 4 5) DO IF ERRORLEVEL 25%%A SET ERR1=%%A IF NOT ERR10==5 GOTO 1 :End REM Clean up the mess and show results SET ERRORLEV=%ERR100%%ERR10%%ERR1% FOR %%A IN (1 10 100) DO SET ERR%%A= ECHO ERRORLEVEL %ERRORLEV%
|
|
This example still handles only 255 error levels (that’s all there is in DOS), but it can be easily adjusted once you understand the basic principles.
To check errorlevels during batch file development, use either COMMAND /Z yourbatch.bat to display the errorlevel of every command executed in MS-DOS 7.* (Windows 95/98), or PROMPT Errorlevel$Q$R$_$P$G in OS/2 Warp (DOS) sessions.
Setting errorlevels
MS-DOS & Windows 9x:
Use ERRORLVL.EXE from OzWoz Software, or SETERLEV.COM 1.0 from Jim Elliott to test batch files that (are supposed to) check on errorlevels.
The syntax couldn’t be simpler:
ERRORLVL number
or
SETERLEV number
where number can be any number from 0 to 255.
A small Kix «one liner» can be used too:
EXIT $ErrLev
If called by a batch like this:
KIX32 ERRORLEVEL.KIX $ErrLev=23
it will return an errorlevel 23 (ERRORLEVEL.KIX would be the name of the kix script mentioned above).
Or use CHOICE.COM, available in all DOS 6.* and up versions, to set an errorlevel:
ECHO 5 | CHOICE /C:1234567890 /N
and
ECHO E | CHOICE /C:ABCDEFGHIJ /N
will both result in errorlevel 5 since both 5 and E are the fifth choice (/C:…) in the corresponding CHOICE commands.
Windows NT 4 and later:
In NT 4 use either
COLOR 00
or
VERIFY OTHER 2> NUL
to set an errorlevel 1.
Windows 2000 and later:
In Windows 2000 and later the EXIT
command accepts an optional exit code, a.k.a. return code or errorlevel, e.g. EXIT /B 1
for errorlevel 1:
EXIT
Quits the CMD.EXE program (command interpreter) or the current batch script.
EXIT [ /B ] [ exitCode ]
/B | Specifies to exit the current batch script instead of CMD.EXE. If executed from outside a batch script, it will quit CMD.EXE. |
exitCode | Specifies a numeric number. If /B is specified, sets ERRORLEVEL that number. If quitting CMD.EXE, sets the process exit code with that number. |
[ Brought to my attention by Maor Conforti. Thanks ]
If you want to set an errorlevel inside a batch file, for example to test an external command used by that batch file, you can use CMD.EXE /K EXIT 6
to set errorlevel 6 and continue.
Do NOT use SET ErrorLevel=6
as this will render the Errorlevel
variable static.
Related stuff
• Use EXIT in Windows 2000 (and later) to set errorlevels.
• See how errorlevels are used to check the availability of third party tools, and how your batch file can even help the user download the tool if it isn’t available.
• This blog entry by Batcheero explains perfectly why you should never SET the ERRORLEVEL variable.
The same goes for other dynamic environment variables like CD (current directory), DATE (current date), TIME (current time), RANDOM (random decimal number between 0 and 32767), CMDEXTVERSION (current Command Processor Extensions version) and CMDCMDLINE (the original command line that invoked the Command Processor).
page last modified: 2022-04-01