try/catch not catching?

Discussion of Photoshop Scripting, Photoshop Actions and Photoshop Automation in General

Moderators: Tom, Kukurykus

undavide

try/catch not catching?

Post by undavide »

Hi (I was writing "Hi Mike" but I stopped, since it's the third or fourth consecutive post that I ask something and he promptly replies By the way thanks very much Mike!),
there's something that I cant get about try/catch.
Take for instance this simplified structure:

Code: Select allvar Obj = function () {

    var win = undefined;

   this.createWin = function () {
      w = new Window('dialog');
      w.preferredSize = [300, 300];
      w.button = w.add('button', undefined, "Fire");
      this.win = w;
   }

   this.initWin = function () {
      this.win.button.onClick = function () { throw new Error("BOOM!") };
   }

   this.runWin = function () {
      this.win.show();
   }
}

try {
    var obj = new Obj();
    obj.createWin();
    obj.initWin();
    obj.runWin();
} catch (e) {
    alert(e.message + "\n" + e.line)
}

If you run it and click the Fire button, an Error is thrown, but I see no alert - I wonder why - nonetheless the Error is caught. This is proved removing the try/catch statements.
Conversely, if you mistype something, like "win" instead of "this.win", the alert shows.
Is there any selective catching going on?!

Thanks

Davide Barranca
http://www.davidebarranca.com
Mike Hale

try/catch not catching?

Post by Mike Hale »

I have noticed this before and it has caused me problems tracking down bugs. I don't know why but errors in event handlers are not caught in a try/catch block unless the block in in the handler function. Changing the callback to this will show the alert.
Code: Select allthis.initWin = function () {
  this.win.button.onClick = function () {
      try{
          throw new Error("BOOM!");
     }catch(e){alert(e.message + "\n" + e.line)}};
}


If you are testing a script in ESTK you can turn off 'Do Not Break on Guarded Exceptions" and the script will stop on the error. Otherwise it's a silent fail and you can be unaware that not all the code in the function completed.

If you are running in Photoshop you have to add the try/catch to the callback function or at least put $.level = 1; at the top of your script to see the error.
undavide

try/catch not catching?

Post by undavide »

For what is worth, here is a post in the Feedback site.

http://feedback.photoshop.com/photoshop ... atch_block

Please add your vote!

Davide