Error Handling in Batch

What Is Error Handling?

Error handling means detecting when something goes wrong (missing file, wrong path, failed command) and reacting to it without crashing the script.

Check If a File Exists

if exist "data.txt" (
  echo File found!
) else (
  echo File missing!
)
      

Errorlevel Basics

Every command sets a special number called errorlevel. 0 = success Non-zero = failure

command
echo %errorlevel%
      

Using Errorlevel to Detect Failures

copy file1.txt backup.txt
if errorlevel 1 (
  echo Copy failed!
) else (
  echo Copy successful!
)
      

Important Note

IF ERRORLEVEL checks “greater or equal”, not equals.

if errorlevel 1 echo Something went wrong
if errorlevel 0 echo Everything OK
      

Safer Number Comparison

if %errorlevel%==0 (
  echo OK
) else (
  echo Error!
)
      

Try/Catch Style (Manual)

Batch doesn't have real try/catch, but you can simulate it:

@echo off

set "errorFlag=0"

copy missing.txt test.txt || set errorFlag=1

if %errorFlag%==1 (
  echo Copy failed!
) else (
  echo Success!
)
      

The Double-Pipe Trick

Command || fallback Runs fallback only if the first command fails.

mkdir testfolder || echo Folder could not be created!
      

The AND Trick

Command && next Runs next only if the first command succeeds.

echo Creating backup... && copy a.txt b.txt
      

Full Example — Safe Delete

@echo off

set "file=test.txt"

if not exist "%file%" (
  echo File does not exist!
  exit /b
)

del "%file%" && echo Deleted successfully! || echo Could not delete!
      

Why Error Handling Matters

What’s Next?

Next you’ll learn how to work with Python lists and tuples — two of the most important data structures.