In a Windows batch file, I am taking an optional parameter that allows the caller to jump to the middle of the batch file and resume from there.
For example:
if [%1] neq [] (
echo Starting from step %1
goto %1
if %errorlevel% neq 0 goto error
)
:step1
:step2
...
goto end
:error
echo Error handler
...
:end
If the supplied parameter is not a valid label, the batch file immediately exits with the error The system cannot find the batch label specified.
Is there any way for me to handle this error and either execute my error handler block, or resume execution of the entire batch file, as if no parameter had been supplied?
Usage: GOTO can only be used in batch files. After a GOTO command in a batch file, the next line to be executed will be the one immediately following the label. The label must begin with a colon [:] and appear on a line by itself, and cannot be included in a command group.
The goto command moves a batch file to a specific label or location, enabling a user to rerun it or skip other lines depending on inputs or events.
At the end of your subroutine, you can jump to the end of the batch file (so that execution falls off the end) by doing a goto :eof . In other words, goto :eof is the return statement for batch file subroutines.
Pressing "y" would use the goto command and go back to start and rerun the batch file. Pressing any other key would exit the batch file.
You could try using findstr on the batch locating the goto target:
findstr /r /i /c:"^:%1" %0>nul
if errorlevel 1 goto error
It's a bit of a hack, but should work.
call :label
spits out the error doesn't spit out an error when stderr is redirected (thanks, Johannes), and doesn't appear to change the error level, but continues with the batch file. You could set a variable after a label to indicate whether execution got that far.
@echo off
call :foo 2>nul
echo %errorlevel%
:bar
echo bar
yields
C:\>test.cmd The system cannot find the batch label specified - foo 1 bar C:\>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With