JavaScript脚本调试错误!~
JavaScript脚本调试错误!~ 解决方法。。
补充:实现版本
JavaScript 1.4
JavaScript 1.5, NES 6.0: added multiple catch clauses (Netscape extension).
ECMA-262, Edition 3
例子:请参考:
Example 2: Throw an object. The following example tests an input string for a U.S. zip code. If the zip code uses an invalid format, the throw statement throws an exception by creating an object of type ZipCodeFormatException.
/*
* Creates a ZipCode object.
*
* Accepted formats for a zip code are:
* 12345
* 12345-6789
* 123456789
* 12345 6789
*
* If the argument passed to the ZipCode constructor does not
* conform to one of these patterns, an exception is thrown.
*/
function ZipCode(zip) {
zip = new String(zip);
pattern = /[0-9]{5}([- ]?[0-9]{4})?/;
if (pattern.test(zip)) {
// zip code value will be the first match in the string
this.value = zip.match(pattern)[0];
this.valueOf = function (){return this.value};
this.toString = function (){return String(this.value)};
} else {
throw new ZipCodeFormatException(zip);
}
}
function ZipCodeFormatException(value) {
this.value = value;
this.message =
"does not conform to the expected format for a zip code ";
this.toString =
function (){return this.value + this.message};
}
/*
* This could be in a script that validates address data
* for US addresses.
*/
var ZIPCODE_INVALID = -1;
var ZIPCODE_UNKNOWN_ERROR = -2;
function verifyZipCode(z) {
try {
z = new ZipCode(z);
}
catch (e) {
if (e instanceof ZipCodeFormatException) {
return ZIPCODE_INVALID;
}
else {
return ZIPCODE_UNKNOWN_ERROR;
}
}
return z;
}
a=verifyZipCode(95060); // returns 95060
b=verifyZipCode(9560;) // returns -1
c=verifyZipCode( "a "); // returns -1
d=verifyZipCode( "95060 "); // returns 95060
e=verifyZipCode( "95060 1234 "); // returns 95060 1234
追问:用finally呢??
答案: 我刚问了下 辰星 在调试Javascript脚本的时候,如果有错误,IE的状态栏里会有个问号[点击此问号],或者弹出错误框,为了尽快找到错误,下面是常用的调试方法:
1,如果出现对象为null或找不不到对象,那就是id,name或DOM写法不对,请检查错误所在的行;
2,如果错误定位到一个函数的调用上,说明函数体有问题,到函数体里找原因。
3,为了加快速度,可以先用/* */注释屏蔽掉一部分代码,逐步检查;
4,可以增加alert(xxx)来看看变量是否得到了期望的值;
5,IE的错误报告往往不准确,比如行18错的话,有时候是19行有问题;
6,为了确保代码能够正确运行,在实在不能确定能否出现错误的时候,用try{}catch{}语句在做
有问题 在问我
QQ466858593
用finally,(用java写的例子,不过是一样的了)
当一个异常抛出时,程序的执行不再是线性的,可能跳过某些代码,甚至会由于没有匹配的catch子句而过早地返回。为了确保某一段代码无论发生什么异常都被执行到,需要使用“finally”关键字。finally程序块会在执行try程序块后的代码之前执行。每个try模块都需要至少一个catch和finally子句。一个成员函数返回调用它的函数有两种途径:一个没有被捕捉到的异常;一个return语句,finally子句总是恰好在成员函数返回前处理。
程序清单:
class FinallyDemo{
static void procA(){
try{
System.out.println( "inside procA ");
throw new RuntimeException( "demo ");
}
finally{
System.out.println( "procA 's finally ");
}
}
static void procB(){
try{
System.out.println( "inside procB ");
return;
}
finally{
System.out.println( "procB 's finally ");
}
}
public static void main(String args[]){
try{
procA();
}catch(Exception e);
procB();
}
}
运行结果:
c:\> java FinallyDemo
inside procA
procA 's finally
inside procB
procB 's finally
上一个:JavaScript截取字符串问题求解
下一个:javascript注册验证的问题?