Windows 10

How To Check Batch File Error

In this tutorial, you’ll learn how to detect and handle errors in a Windows batch file using the built-in ERRORLEVEL variable. A batch file contains a series of DOS (Disk Operating System) commands, and ERRORLEVEL helps determine whether the previous command was successful.
 

🧠 What is ERRORLEVEL?

ERRORLEVEL stores the return code of the last executed command. It helps you perform conditional logic based on the result:

  • ✅ ERRORLEVEL = 0 → Success
  • ❌ ERRORLEVEL ≥ 1 → Error or failure (depends on the program)
 

🧪 Example 1: Check for Error and Redirect Flow

If the last command returns an error. The ERRORLEVEL variable will contains 1. If there is no error. The ERRORLEVEL variable will contains 0.

if ERRORLEVEL 1 goto errorHandling
REM No error here; ERRORLEVEL == 0

:errorHandling
echo An error has occurred.

This script jumps to the :errorHandling label only if an error is detected.
 

📌 Example 2: Display a Custom Error Message
if ERRORLEVEL 1 echo Unsuccessful

This prints Unsuccessful only if the previous command failed.
 

🔍 Example 3: Display the Error Code
echo %errorlevel%

This line shows the current ERRORLEVEL value. Useful for debugging or logging.
 

🔄 Use Case: Chaining Commands with Error Checks

You can chain commands and take specific actions if any step fails:

@echo off
copy file1.txt backup.txt
if ERRORLEVEL 1 (
    echo Failed to copy file1.txt
    exit /b
)

del file1.txt
if ERRORLEVEL 1 (
    echo Failed to delete file1.txt
)

 

⚙️ Best Practices
  • ✅ Always check ERRORLEVEL after critical operations like copy, move, delete, or external command execution.
  • 🔄 Use exit /b to exit early from the script in case of a fatal error.
  • 🧪 Consider logging errors to a file for auditing.

Using ERRORLEVEL in your batch files helps make your scripts smarter, safer, and easier to debug.
 

Leave a Reply

Your email address will not be published. Required fields are marked *