faqts : Computers : Programming : Languages : JavaScript : Language Core : Exception/Error handling

+ Search
Add Entry AlertManage Folder Edit Entry Add page to http://del.icio.us/
Did You Find This Entry Useful?

60 of 73 people (82%) answered Yes
Recently 5 of 10 people (50%) answered Yes

Entry

Is there an exception/error handling mechanism in core JavaScript?

Jul 31st, 2001 05:38
Thor Larholm,


Netscape's JavaScript till version 1.3 (which is the version around in 
NN4 since NN4.06) has no error/exception handling mechanism in the core 
language. JavaScript 1.4 (which is only around in Netscape's server 
products) introduced
  try
  catch
exception handling and
  throw
exception throwing, JavaScript 1.5 which is (will be) around in NN6 
further added the 
  finally 
clause for try catch.
JScript 5 also supports
  try
  catch
  finally
and 
  throw
though the exception/error object differs between JavaScript and 
JScript (at least at the time of writing this, it is however expected 
that the final releases of JavaScript 1.5 and JScript 5.5 will be ECMA 
compliant).
Current inspection code of the form
  try {
    f();
  }
  catch (e) {
    var r = '';
    for (var p in e)
      r += p + ': ' + e[p] + '\n';
    alert(r);
  }
shows
  number: -2146823281
  description: object expected
with JScript 5 in IE and shows
  message: f is not defined
  name: ReferenceError
with JavaScript 1.5 in NN6. As the ECMAScript edition 3 standard 
prescribes
  message
and
  name
properties for
  Error
objects it seems that Netscape's JavaScript is already compliant with 
the standard in this regard while JScript has to catch up.

So how can we use that in client side JavaScript today? That is not 
easy at least in a cross browser way. 

For Netscape you can safely use 
JavaScript1.4/1.5 SCRIPT blocks e.g.
  <SCRIPT LANGUAGE="JavaScript1.4">
  try { ... } catch (e) { ... }
  </SCRIPT>
and
  <SCRIPT LANGUAGE="JavaScript1.5">
  try { ... } catch (e) { ... }
  </SCRIPT>
which NN6 will execute correctly while NN4 and earlier ignore these.

IE5 has conditional comments. Try catch is implemented in JScript5. So 
for IE you can use this

<!--[if GTE IE 5]>
<script Language="JavaScript">
  try { ... } catch (e) { ... }
</script>
	
<![endif]-->

Earlier versions of IE (<5) and Netscape ignore this.


So combining the code for NN6 and IE5 you can handle exceptions for 
both the browsers. However for the earlier versions we can't handle 
using TRY CATCH.