How-to: Error Handling in a batch file

When an executable program runs and completes a task, it will return an Exit Code indicating success or failure. A batch file or batch subroutine can also emulate this behaviour by setting an exit code with EXIT /b

A popular way to branch on an error, is to use the redirection operators for success && and failure || as shown below:

@Echo off
SomeCommand && (
  Echo success
) || (
  Echo failed/error
)

The code stub above can be expanded, instead of just an ECHO statement, you could CALL a subroutine or use EXIT /b to close the script immediately. This will also work to test the ERRORLEVEL within a parenthesized block of code.

There is one gotcha which is that the success/failure state is evaluated on each line, so if you have multiple lines/commands and the last command in the success branch raises an error, then the error branch will fire. To avoid that make sure that last command in the success branch is (call ), which does nothing except set the ERRORLEVEL to 0.

A second problem with the redirection operators is that they make the assumption that a successful operation will return an ERRORLEVEL of 0 and a failure will return some non-zero exit code. This is not always the case, the DEL command will return zero even when it fails to delete and the ROBOCOPY command will return non zero exit codes even when it does a successful copy.

To test for a specific ERRORLEVEL, use an IF command with the %ERRORLEVEL% variable. n.b. Some errors may return a negative number.

@Echo off
SomeCommand
IF %ERRORLEVEL% NEQ 0 (Echo An error was found &Exit /b 1)

If the batch file is being executed as a scheduled task, then exiting with an error code will be logged as a failed task.
You can monitor the event log to discover those failures.

“If error is corrected whenever it is recognised as such, the path of error is the path of truth.” ~ Hans Reichenbach

Related commands:

Errorlevel - CMD's handing of Exit codes and the %ERRORLEVEL% variable.
Robocopy exit codes
How-to: Conditional Execution - if command1 succeeds then execute command2
List of ERRORLEVEL values set by internal cmd.exe commands - Stackoverflow /Aacini.


 
Copyright © 1999-2022 SS64.com
Some rights reserved