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 have a batch file that runs a couple executables, and I want it to exit on success, but stop if the exit code <> 0. How do I do this?
asked Aug 10, 2010 at 18:12
Sounds like you’ll want the «If Errorlevel» command. Assuming your executable returns a non-0 exit code on failure, you do something like:
myProgram.exe
if errorlevel 1 goto somethingbad
echo Success!
exit
:somethingbad
echo Something Bad Happened.
Errorlevel checking is done as a greater-or-equal check, so any non-0 exit value will trigger the jump. Therefore, if you need to check for more than one specific exit value, you should check for the highest one first.
answered Aug 10, 2010 at 18:20
HellionHellion
1,74028 silver badges36 bronze badges
5
You can also use conditional processing symbols to do a simple success/failure check. For example:
myProgram.exe && echo Done!
would print Done!
only if myProgram.exe
returned with error level 0.
myProgram.exe || PAUSE
would cause the batch file to pause if myProgram.exe returns a non-zero error level.
answered Aug 11, 2010 at 5:55
4
A solution better than Hellion’s answer is checking the %ERRORLEVEL%
environment variable:
IF %ERRORLEVEL% NEQ 0 (
REM do something here to address the error
)
It executes the IF
body, if the return code is anything other than zero, not just values greater than zero.
The command IF ERRORLEVEL 1 ...
misses the negative return values. Some progrmas may also use negative values to indicate error.
BTW, I love Cheran’s answer (using &&
and ||
operators), and recommend that to all.
For more information about the topic, read this article
answered Sep 24, 2019 at 11:47
Mohammad DehghanMohammad Dehghan
17.7k3 gold badges55 silver badges70 bronze badges
By default when a command line execution is completed it should either return zero when execution succeeds or non-zero when execution fails. When a batch script returns a non-zero value after the execution fails, the non-zero value will indicate what is the error number. We will then use the error number to determine what the error is about and resolve it accordingly.
Following are the common exit code and their description.
Error Code | Description |
---|---|
0 | Program successfully completed. |
1 | Incorrect function. Indicates that Action has attempted to execute non-recognized command in Windows command prompt cmd.exe. |
2 | The system cannot find the file specified. Indicates that the file cannot be found in specified location. |
3 | The system cannot find the path specified. Indicates that the specified path cannot be found. |
5 | Access is denied. Indicates that user has no access right to specified resource. |
9009 0x2331 |
Program is not recognized as an internal or external command, operable program or batch file. Indicates that command, application name or path has been misspelled when configuring the Action. |
221225495 0xC0000017 -1073741801 |
Not enough virtual memory is available. It indicates that Windows has run out of memory. |
3221225786 0xC000013A -1073741510 |
The application terminated as a result of a CTRL+C. Indicates that the application has been terminated either by the user’s keyboard input CTRL+C or CTRL+Break or closing command prompt window. |
3221225794 0xC0000142 -1073741502 |
The application failed to initialize properly. Indicates that the application has been launched on a Desktop to which the current user has no access rights. Another possible cause is that either gdi32.dll or user32.dll has failed to initialize. |
Error Level
The environmental variable %ERRORLEVEL% contains the return code of the last executed program or script.
By default, the way to check for the ERRORLEVEL is via the following code.
Syntax
IF %ERRORLEVEL% NEQ 0 ( DO_Something )
It is common to use the command EXIT /B %ERRORLEVEL% at the end of the batch file to return the error codes from the batch file.
EXIT /B at the end of the batch file will stop execution of a batch file.
Use EXIT /B < exitcodes > at the end of the batch file to return custom return codes.
Environment variable %ERRORLEVEL% contains the latest errorlevel in the batch file, which is the latest error codes from the last command executed. In the batch file, it is always a good practice to use environment variables instead of constant values, since the same variable get expanded to different values on different computers.
Let’s look at a quick example on how to check for error codes from a batch file.
Example
Let’s assume we have a batch file called Find.cmd which has the following code. In the code, we have clearly mentioned that we if don’t find the file called lists.txt then we should set the errorlevel to 7. Similarly, if we see that the variable userprofile is not defined then we should set the errorlevel code to 9.
if not exist c:lists.txt exit 7 if not defined userprofile exit 9 exit 0
Let’s assume we have another file called App.cmd that calls Find.cmd first. Now, if the Find.cmd returns an error wherein it sets the errorlevel to greater than 0 then it would exit the program. In the following batch file, after calling the Find.cnd find, it actually checks to see if the errorlevel is greater than 0.
Call Find.cmd if errorlevel gtr 0 exit echo “Successful completion”
Output
In the above program, we can have the following scenarios as the output −
-
If the file c:lists.txt does not exist, then nothing will be displayed in the console output.
-
If the variable userprofile does not exist, then nothing will be displayed in the console output.
-
If both of the above condition passes then the string “Successful completion” will be displayed in the command prompt.
Loops
In the decision making chapter, we have seen statements which have been executed one after the other in a sequential manner. Additionally, implementations can also be done in Batch Script to alter the flow of control in a program’s logic. They are then classified into flow of control statements.
S.No | Loops & Description |
---|---|
1 | While Statement Implementation
There is no direct while statement available in Batch Script but we can do an implementation of this loop very easily by using the if statement and labels. |
2 | For Statement — List Implementations
The «FOR» construct offers looping capabilities for batch files. Following is the common construct of the ‘for’ statement for working with a list of values. |
3 | Looping through Ranges
The ‘for’ statement also has the ability to move through a range of values. Following is the general form of the statement. |
4 | Classic for Loop Implementation
Following is the classic ‘for’ statement which is available in most programming languages. |
Looping through Command Line Arguments
The ‘for’ statement can also be used for checking command line arguments. The following example shows how the ‘for’ statement can be used to loop through the command line arguments.
Example
@ECHO OFF :Loop IF "%1"=="" GOTO completed FOR %%F IN (%1) DO echo %%F SHIFT GOTO Loop :completed
Output
Let’s assume that our above code is stored in a file called Test.bat. The above command will produce the following output if the batch file passes the command line arguments of 1,2 and 3 as Test.bat 1 2 3.
1 2 3
S.No | Loops & Description |
---|---|
1 | Break Statement Implementation
The break statement is used to alter the flow of control inside loops within any programming language. The break statement is normally used in looping constructs and is used to cause immediate termination of the innermost enclosing loop. |
Razvedka2020 40 / 35 / 9 Регистрация: 01.01.2014 Сообщений: 201 |
||||
1 |
||||
Как скрыть ошибку выполнения?22.02.2020, 22:15. Показов 13224. Ответов 8 Метки нет (Все метки)
Здравствуйте уважаемые форумчане. Решил навести красоту в своих скриптах и столкнулся с неприятностями, а именно с отображением ошибок (код импровизированный):
Вопрос: как можно избавится от отображения ошибок?
0 |
alpap 4332 / 2122 / 661 Регистрация: 26.04.2015 Сообщений: 6,823 |
||||
23.02.2020, 03:54 |
2 |
|||
1 |
Razvedka2020 40 / 35 / 9 Регистрация: 01.01.2014 Сообщений: 201 |
||||||||
23.02.2020, 05:45 [ТС] |
3 |
|||||||
Я может быть не понимаю ваш ответ, но в строке 3 я уже пробовал конструкцию (она не помогла и я ее закоментировал)
Это не помогает избавится от вывода ошибки, так же как и
Результат одинаков, на скриншоте.
0 |
6567 / 1770 / 301 Регистрация: 10.12.2013 Сообщений: 6,236 |
|
23.02.2020, 07:11 |
4 |
Решил навести красоту в своих скриптах И тут же воткнёшься носом в неразрешимое противоречие понятия красоты.
0 |
5846 / 2559 / 1006 Регистрация: 06.06.2017 Сообщений: 8,741 |
|
23.02.2020, 07:16 |
5 |
но в строке 3 я уже пробовал конструкцию А где там
0 |
Razvedka2020 40 / 35 / 9 Регистрация: 01.01.2014 Сообщений: 201 |
||||
23.02.2020, 07:20 [ТС] |
6 |
|||
А где там 2>nul спереди? Можно для особо «одаренных» пояснить что за
или где про это почитать?
0 |
6567 / 1770 / 301 Регистрация: 10.12.2013 Сообщений: 6,236 |
|
23.02.2020, 07:47 |
7 |
Сообщение было отмечено Razvedka2020 как решение Решение Программная абстракция существования стандартных файловых потоков в виде их описателей (handles) Код ECHO "раз два три-пять зайтчик погулять" 1 > NUL 2 > &1 интерпретатор распознает сочетание 1 > NUL ( {одинокая цифра}
1 |
5846 / 2559 / 1006 Регистрация: 06.06.2017 Сообщений: 8,741 |
|
23.02.2020, 08:11 |
8 |
Сообщение было отмечено Razvedka2020 как решение Решение
1 |
40 / 35 / 9 Регистрация: 01.01.2014 Сообщений: 201 |
|
23.02.2020, 08:14 [ТС] |
9 |
Большое вам всем человеческое спасибо. Не зря говорят: Век живи, век учись…
0 |
Как сделать обработку исключений в CMD?
В python например так:
try:
...
print("Ошибок нет! ")
except:
print("Ошибка!")
-
Вопрос заданболее года назад
-
499 просмотров
КОМАНДА1 && КОМАНДА2
— вторая команда выполняется, если первая завершилась без ошибок.
КОМАНДА1 || КОМАНДА2
— вторая команда выполняется, если первая завершилась с ошибкой.
КОМАНДА && echo Ошибок нет! || echo Ошибка!
(Для объединения нескольких команд в составную можно использовать скобки, переносы строк или знак &
между командами в одной строке. Для размещения одной простой команды на нескольких строках можно использовать ^
в конце переносимой строки…)
Пригласить эксперта
-
Показать ещё
Загружается…
03 июн. 2023, в 23:42
1500 руб./за проект
03 июн. 2023, в 22:36
5000 руб./за проект
03 июн. 2023, в 19:30
750 руб./в час