Copy link to clipboard
Copied
I'm trying to get a try/catch to work and I thought that the following code snippet would be correct:
openDoc();
function openDoc() {
try {
app.documents.length >= 2; // This is not working as expected... ???
I am looking to test for at least two open files before the script will run.
The first time it is run with a single open doc it does not move onto the catch, it passes the try when it should not. If I then run the script a second time directly afterwards, it does work as intended and it throws the catch error that only one file is open.
I obviously have not posted the full code and it does work with no files open, moving onto the catch error message.
So is this code snippet wrong? Or if this snippet is correct, is the problem potentially elsewhere in the try/catch routine that I have not shown (I know, a loaded question)?
1 Correct answer
Isn't it better to use condition instead of try...catch statement, like if (documents.length > 1)
Explore related tutorials & articles
Copy link to clipboard
Copied
Isn't it better to use condition instead of try...catch statement, like if (documents.length > 1)
Copy link to clipboard
Copied
Kukurykus is correct about using an if statement. The try catch block will only work if the code throws an error. It's used to keep your script from stopping, not really for conditional statements.
Copy link to clipboard
Copied
if you really want to use try... catch, then you can use the throw operator to generate an error 🙂
openDoc();
function openDoc() {
try {
if (app.documents.length < 2) throw ("too few docs")}
catch (e) {alert (e)}}
Copy link to clipboard
Copied
Thank you Kukurykus – the if/else works as expected!
Chuck, thanks, I am still learning where/how to use these statements...
Thank you too DmitryEgorov – I am not exactly wedded to using try/catch in this case, it is just that I copied an existing code block that was testing for no open documents and attempted to expand it' s use.

