Last Updated: February 25, 2016
· zaus

Pause on error in Batch File

Don't you hate it when you write a beautiful batch script, then run it only to discover it fails miserably? Isn't it even worse when it just flashes onscreen too quickly to discover what went wrong? But assuming things went fine, you don't want to "press any key to continue" every time, right?

Therefore, to pause on error in a batch script just check the error level and pause:

if NOT ["%errorlevel%"]==["0"] pause

Don't check for 1, even though it automatically checks for anything equal-to-or-greater (source), because technically scripts can return negative numbers. I also prefer "string" checking rather than IF %errorlevel% NEQ 0 just for exactness.

And if you want your batch file to expose the last error, exit with the same code:

if NOT ["%errorlevel%"]==["0"] (
    exit /b %errorlevel%

And if you're feeling really fresh, repeat it with a reusable function:

-- do stuff --


-- do more stuff --


:: ======== FN ======

:: /// check if the app has failed
[AT]echo off
if NOT ["%errorlevel%"]==["0"] (
    exit /b %errorlevel%

(note the use of [AT] rather than @ due to coderwall auto-mention formatting)

2 Responses
Add your response

FYI you can simplify this to a one liner

DIR nofile || (PAUSE && EXIT /B 1)

You can even create a pseudo "macro" for this in a batch script:

SET errorhandler=^|^| ^(PAUSE ^&^& EXIT /B 1^)

DIR .  %errorhandler%
DIR nofile %errorhandler%
over 1 year ago ·

@steve-jansen Interesting. Does this work when calling another file, or 'subroutine'? i can't get CALL <somefile> %errorhandler% to behave.

And if you still want to 'rethrow' the error, the following seems to work:

SET errorhandler=^|^| ^(PAUSE ^&^& EXIT /B %errorlevel%^)
over 1 year ago ·