CONTEXT:
Hello,
I have 2 notebooks, lets call them "Main.nb" and "FileProcessing.nb". In my "Main.nb" I have a Do loop where the iterating parameter goes over 300 .csv files which I want to process. I wrote the code for the processing into the "FileProcessing.nb".
However not every .csv file is in the right format - e.g. sometimes something is missing, hence the file is too short. I wrote tests into the "FileProcessing.nb", so as it is evaluating it can at several moments discover problems (= a test return False). In such case I want to stop evaluating the "FileProcessing.nb" and continue the Do loop in "Main.nb" with next value of the parameter.
QUESTION:
Is there a way, how can I at several points in the "Fileprocessing.nb" decide if I want to proceed or to stop and continue in the Do loop in "Main.nb"?
TOY PROBLEM:
I have the "Main.nb" and "FileProcessing.nb" in the same folder. The "Main.nb" contains
dir = SetDirectory[NotebookDirectory[]]
Table[
NotebookEvaluate[FileNameJoin[{dir, "FileProcessing.nb"}]],
{filenumber, 4}
]
and the "FileProcessing.nb" contains
Print["Hello world! ", 100 + filenumber]
Return["Succesfully returned."]
If[
filenumber < 3,
Print["Test OK."],
Print["Too big."]; Return["Stopped."]
]
Print["Hallo Welt! ", 100 + filenumber, "\n"]
There is Return
on the second line, so rest of the code does not evaluate. It prints fourtimes "Hello world!" with number (101-104) in the "Main.nb" and returns table with fourtimes "Succesfully returned.".
As far, it behaves as I expected. It is "the proof" that Return[]
works. However, I want to return only if something "bad" happends (= a test returns False). So if you remove the second line Return["Succesfully returned."]
, then there is Return
inside If
. The idea is that if the test filenumber < 3
is false, the rest of the notebook content should not be evaluated. But Return
inside If
means in fact something different. It does not return from the whole notebook, but only from the If statement and the rest of the code is always executed.
When I realised that, I tried to wrap NotebookEvaluate
in Catch
and instead of Return
use Throw
, but it does not work. It gives the following error
Throw::nocatch: Uncaught Throw[Stopped.] returned to top level.
Then I found in "NotebookEvaluate" documentation page that "The cells of the notebook are evaluated in a dialog subsession.", but I have not been able to use this information to my advantage...
PS: I use version 11.3 and at home (where I write this question) I have 12.1.
I would be very grateful for any help and guidance.
NotebookEvaluate
. That would make it much more straightforward to achieve what you want... $\endgroup$