jexjlw
Last Updated: February 25, 2016
·
12.95K
· zaus
D940dd93751cea6229c4b9b2098b7f39

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"] (
    pause
    exit /b %errorlevel%
)

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

-- do stuff --

CALL :CHECK_FAIL

-- do more stuff --

CALL :CHECK_FAIL

:: ======== FN ======
GOTO :EOF

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

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

Say Thanks
Respond

2 Responses
Add your response

12337
D3b2094f1b3386e660bb737e797f5dcc

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 ·
12614
D940dd93751cea6229c4b9b2098b7f39

@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 ·
Filed Under