HOWTO · Batch
How to Handle Errors in Batch Files
Learn how to check command exit codes in Windows batch files, branch on success or failure, log diagnostic output, and return a useful status.
On this page
To handle errors in a Windows .bat or .cmd file, check the command’s exit code immediately and choose a branch that reports the problem or continues on success. Batch commands conventionally return 0 for success and nonzero codes for failure, but a particular nonzero code can identify a specific condition. %ERRORLEVEL% exposes the current status, while IF ERRORLEVEL tests whether it is at least a given value.
How Batch Error Levels Work
A command returns an exit code when it finishes. By convention, 0 means success; a nonzero value signals that the command did not complete successfully, though its exact meaning depends on that command. A batch script can use this status to decide what to do next.
Use %ERRORLEVEL% to read the current code, or use IF ERRORLEVEL n to test a threshold. IF ERRORLEVEL n is true when the current code is greater than or equal to n, not only when it equals n. Check the status directly after the command whose result matters so another command does not replace it.
Check a Command’s Exit Code
For a threshold check, put the larger threshold first if you test several values; otherwise a higher code also satisfies each lower threshold. For a direct comparison, capture %ERRORLEVEL% immediately after the command and compare the saved value.
This example checks whether the text ready appears in a value. Change message to a different word to see the failure branch. The saved value comes directly from findstr, before any echo command can replace it. This Windows Command Prompt example is unexecuted in the supplied packet.
@echo off
set "message=ready"
echo(%message%| findstr /c:"ready" >nul
set "command_status=%ERRORLEVEL%"
if "%command_status%"=="0" (
echo Match found.
) else (
echo Match not found.
)
In a parenthesized block, %variable% references are expanded when the block is parsed. The status is captured before entering the block, so the comparison uses the saved result. For exact status handling, compare that saved value; IF ERRORLEVEL n instead tests whether the current status is at least n.
Handle Errors with Conditional Commands
Use && to run the next command only when the preceding command succeeds, and || to run the next command only when it fails. These operators are useful for short branches:
some_command && echo Success || echo Failure
For longer handling, an IF block is easier to read. IF ERRORLEVEL 1 checks for a code of at least 1, which covers the usual nonzero failure statuses but does not distinguish their meanings. For exact status handling, capture %ERRORLEVEL% immediately and compare the saved value as shown above.
Build and Test a Failure and Success Example
This script creates a fresh demonstration directory under the Windows temporary directory using a randomized name. It never deletes a path. If directory creation fails or the expected input is already present, it stops with setup status 2. It checks that the input is absent before running type; the expected failure message is printed only when the file is still absent. It then creates the input, checks that write operation, and reads the same file. This Windows Command Prompt example is unexecuted in the supplied packet.
Run this example:
@echo off
set "demo_dir=%TEMP%\batch-error-demo-%RANDOM%-%RANDOM%"
set "demo_file=%demo_dir%\input.txt"
if exist "%demo_dir%" (
echo Setup failed: the randomized demo directory is already present.
exit /b 2
)
mkdir "%demo_dir%" >nul 2>&1
if errorlevel 1 (
echo Setup failed: could not create the fresh demo directory.
exit /b 2
)
if exist "%demo_file%" (
echo Setup failed: the demo input is already present.
exit /b 2
)
type "%demo_file%" >nul 2>&1
set "command_status=%ERRORLEVEL%"
if not "%command_status%"=="0" (
if not exist "%demo_file%" (
echo Failure: input.txt was not found.
) else (
echo Failure: input.txt could not be read.
exit /b 1
)
) else (
echo Read input.txt successfully.
)
>"%demo_file%" echo ready
if errorlevel 1 (
echo Setup failed: could not create input.txt.
exit /b 2
)
type "%demo_file%" >nul 2>&1
if errorlevel 1 (
echo Failure: input.txt could not be read.
exit /b 1
)
echo Success: input.txt contains ready.
exit /b 0
The first check demonstrates the expected missing-file failure, and the later read demonstrates success. The script returns 0 after the successful read, 1 if a read fails, and 2 if setup cannot establish a fresh demo directory or input file. It leaves its uniquely named directory in %TEMP% so it cannot remove unrelated data; delete that specific directory manually after reviewing it if you want to clean up.
Log Errors and Return a Useful Status
A useful handler identifies the failed operation, preserves diagnostic output when needed, and returns a nonzero status to the caller. Append both standard output and standard error to a log with >> "%LOGFILE%" 2>&1, then check the command’s status immediately; redirection captures output but does not handle the failure by itself.
For example, after setting a suitable log path, a script can run a command with >> "%LOGFILE%" 2>&1, save %ERRORLEVEL% on the next line, and branch on that saved value. On failure, print a message that names the operation and log file, then use exit /b 1; on success, use exit /b 0. Choose log paths that the script’s user can write to, and avoid assuming that every nonzero code has the same cause.