Site Navigation

Thursday, November 1, 2007

bug 184 - The catch to Try Catch Finally in IE

Issue: #184
Affects: IE5, IE5.5, IE6, IE7
Fixed In: IE8 RC1


Like several programming languages, JavaScript offers the try/catch/finally block. This allows for errors to be handled gracefully, rather than halting the page execution.

You place code that might cause an error in the try section. If an error occurs, the catch section will allow you to handle it, and the finally block is always executed regardless if an error occurred or not.

The finally part is optional, as is the catch part. (wikipedia reference)

However, in IE, if you don't supply a catch statement, your finally statement will never be called!

Example:

<script type="text/javascript">
//this works
try {
window.undefinedMethod();
} catch(e){
alert('Error: ' + e);
} finally {
alert('about to print...');
window.print();
}

//this fails in IE
try {
window.undefinedMethod();
} finally {
alert('about to print...' +
'\nBut IE will never show this message' +
'\nNor will it call print()');
window.print();
}
</script>



Known Workarounds: One. Although the catch is supposed to be optional, to make IE work properly include an empty catch.

Example Workaround Code:

<script type="text/javascript">
try {
window.undefinedMethod();
} catch(e){
//ensure IE executes the finally section
} finally {
alert('about to print...' +
'\nIE will show this message' +
'\nand it will call print()');
window.print();
}
</script>



Related Issues: None.