views:

1215

answers:

3

I'm using a try-catch block in the following Actionscript 3 code:

try {
    this._subtitle = new SubtitleController(subtitlePath, _framerate);
    this._subtitle.addEventListener(Event.COMPLETE, subtitleLoaded);
}
catch (e:Error) {
    trace('subtitle not found');
}

The SubtitleController constructor then tries to load the subtitlePath and throws an Error #2044: Unhandled ioError, but the error is not caught by the try statement. The error is simply thrown like no try statement ever existed.

Sure, I can replace that code with

this._subtitle.addEventListener(IOErrorEvent.IO_ERROR, function (ev:Event) { trace('subtitle not loaded'); });
this._subtitle = new SubtitleController(subtitlePath, _framerate);
this._subtitle.addEventListener(Event.COMPLETE, subtitleLoaded);

and it almost works, it stops trowing that error, but throws another one instead.

But isn't the whole point of try-catch blocks to do that? Why does it not work with the try-catch, but it does work with a regular event listener?

A: 

looks like you catch the error inside the block?

linjunhalida
not sure what you mean, could you elaborate, please?
evilpenguin
+5  A: 

IOErrors/NetworkErrors are asynchronous errors. They are not thrown when the method causing them is called as normal runtime errors. Otherwise the execution would have have to stop completely until a (for example) a file is completely loaded ...

Theo.T
ah.. makes sense now. so for any other error expect i/o and network errors, it should work, right?
evilpenguin
+2  A: 

Basically, since the call is async a try..catch..finally block won’t do you a beans bit of good. It takes a while for the loader to determine the url is bad and then it dispatches the IO_ERROR event. -http://www.mattmaher.net/flexible_code/index.php/2008/01/10/urlloader-stream-error-handling/

Theo is correct, I would merely add to use the IOErrorEvent Class of the flash.events package to handle this for anyone that did not know the method.

var loader:URLLoader = new URLLoader();
loader.load(new URLRequest("test.mp3"));
loader.addEventListener(IOErrorEvent.IO_ERROR, onIOError);
function onIOError(e:IOErrorEvent):void
{
trace("An IO Error has occured.\n\n", e);
}

If your working with a Loader object and not the URLLoader, remember that you need to listen to the contentLoaderInfo property of the Loader object as follows.

var loader:Loader = new Loader();
addChild(loader);

loader.contentLoaderInfo.addEventListener(IOErrorEvent.IO_ERROR, onIOError);
loader.load(new URLRequest("path/to/asset"));

function onIOError(e:IOErrorEvent):void
{
    trace("An IO Error has occured.\n\n", e);
}

Brian Hodge blog.hodgedev.com hodgedev.com

Brian Hodge