jscript 5.0中的新特性
jscript 5.0唯一的改变是引入了错误处理。
java风格的try和catch结构在jscript 5.0中得到了支持。例如:
function getsomekindofindexthingy() {
try {
// if an exception occurs during the execution of this
// block of code, processing of this entire block will
// be aborted and will resume with the first statement in its
// associated catch block.
var objsomething = server.createobject (“somecomponent”);
var intindex = objsomething.getsomeindex();
return intindex;
}
catch (exception) {
// this code will execute when *any* exception occurs during the
// execution of this function
alert (‘oh dear, the object didn’t expect you to do that’);
}
}
内建的jscript error对象有3个属性,它们定义了上次的运行期错误。可在catch块中使用它们获得有关错误的更多信息。
alert (error.number); // gives the numeric value of the error number
// and the result with 0xffff to get a ‘normal’ error number in asp
alert (error.description); // gives an error desciption as a string
假如你想招抛出自己的错误,可用一个定制的异常对象引发一个错误(或异常)。然而,由于没有内建的异常对象,必须自己定义一个结构:
// define our own exception object
function myexception (intnumber, strdescripton, strinfo) {
this.number = intnumber; // set the number property
this.description = strdescription; // set the description property
this.custominfo = strinfo; // set some ‘information’ property
}
这样的对象可用来在页面中引发定制的异常。这通过使用throw关键字,然后检查catch块中的异常类型来实现:
function getsomekindofindexthingy() {
try {
var objsomething = server.createobject (“somecomponent”);
var intindex = objsomething.getsomeindex();
if (intindex == 0) {
// create a new myexception object
theexception = new myexception (0x6f1, “zero index not permitted”,
“index_err”);
throw theexception;
}
catch (objexception) {
if (objexception instanceof myexception) {
// this is one of our custom exption objects
if (objexception.category == “index_err”) {
alert (‘index error: ‘ + objexception.description);
else
alert (‘undefined custom error: ‘ + objexception.description);
}
else
// not “our” exception, so display it and raise to next higher routine
alert (error.description + ‘ (‘ + error.number + ‘)’);
throw exception;
}
}
}
