Batch Error Handling

Introduction

Batch scripts fail silently by default. Error handling lets you detect failures, show useful messages, log issues, and keep your scripts stable.

1. Checking Error Levels

Every command returns an exit code. %ERRORLEVEL% stores the last exit code.

dir C:\NonexistentFolder
echo Error level: %ERRORLEVEL%
    

2. IF ERRORLEVEL

robocopy C:\A C:\B
if errorlevel 1 echo Something went wrong!
    

Important: if errorlevel 1 means “1 or greater”.

if %ERRORLEVEL% neq 0 echo Error occurred!
    

3. Using || and &&

Shortcut operators for success and failure.

mkdir testfolder && echo Created successfully
mkdir testfolder || echo Failed to create folder
    

4. Prevent Script from Stopping: `cmd /c`

Useful when commands may fail.

cmd /c del file.txt || echo Could not delete file.
    

5. Turn Off Default Error Printing

@echo off
setlocal enabledelayedexpansion
    

6. Simple Try/Catch Simulation

Batch has no real try/catch, but you can simulate it.

call :tryBlock
if %ERRORLEVEL% neq 0 call :catchBlock
exit /b

:tryBlock
  dir C:\InvalidFolder
  exit /b %ERRORLEVEL%

:catchBlock
  echo An error happened!
  exit /b
    

7. Logging Errors to a File

dir C:\Invalid 2>>errors.log
if %ERRORLEVEL% neq 0 echo Logged error to file.
    

8. Robust Error Message Template

if %ERRORLEVEL% neq 0 (
  echo [ERROR] Command failed at %date% %time%
)
    

Summary