# Error Handling in FOR Loop



## bushead (Jun 29, 2012)

Hi,

I'm just trying to use some basic standard dos commands to perform the following job. No matter what I try the script
1) Read the contents of a file (no delimiters just one entry per line)
2) based on the contents loop through the file performing a command based on the name in the file (i.e. file contains jon / bob / james, so the file will be calling jon.bat, bob.bat and james.bat)
Here's where I am getting stuck. When an error occurs I want to error out to a seperate step which will invoke a second call to find out the reason based on the file i.e. (calls an batch file such why.bat jon, why.bat bob, why.bat james)
3) for all of the above I write out a log file where the value in the file is different.

Here's a simplistic view of the script (obviously the reality is that I am trying to achieve something else but this serves to show the issue).


I realise the script is not very good but I didn't want to stick the whole job I'm doing because the number of parameters would make it to big.

@@echo off
echo ## CURRENT DIRECTORY=%CD%
REM #######################################################################
REM ## START LOOP
REM #######################################################################
set scopefile=scope.txt
for /f %%w in (%CD%\%scopefile%) do ( 
echo %%w
echo Logfile set to %CD%\%%w.log
echo.
echo starting %%w
%CD%\%%w.dat >> %%w.log
ECHO %ERRORLEVEL%
IF %ERRORLEVEL% NEQ 0 (
echo "%%w Failed Calling Script to find out why"
call :workflowerror %%w
) ELSE (
echo.
echo Workflow %%w completed successfully!
)
)
REM #######################################################################
REM ## END LOOP
REM #######################################################################
GOTO :QUIT
### ERROR FUNCTIONS
:workflowerror
echo.
echo %1 Failed Now establishing why!
(%CD%\why.bat %1)
ECHO %ERRORLEVEL%
IF %ERRORLEVEL% NEQ 0 call :workflowstatuserror %1
REM ##EXIT
:workflowstatuserror
echo.
echo Why checked failed to establish the reason for %1 failure
exit 1
echo.
REM ## EXIT
:QUIT


----------

