JScript点滴 |
|
JScript的try{throw(Exp)}catch(Exception){}
大多人习惯用 <!-- --> 来掩盖JavaScript中的错误。 其实这是不全面的。 例如滥用document.domain,上面的符号就不起作用, 错误信息还是会弹出来让用户看到。 JavaScript提供了实时的错误处理 try,throw,catch 下面用例子说明怎样使用这些 例子一:学习基本用法 <html> <body></body> <script> function exec(str) { try{ execScript(str); } catch(x){ for(i in x){ document.body.innerHTML+=i+":"+x[i]+"<br>"; } } } exec("status=body"); exec("document.dowhat(i)"); </script> <script> try { if(0)throw("this is not a exception!"); if(1)throw("Report:Error Existed!"); } catch(x){status=x}; </script> </html> 例子二: 防止被嵌入到其他网页: <html> <script> try { if(parent)if(parent.document.domain!=document.domain) parent.location.href="about:blank";//其实这句没有可能执行 } catch(x){ //如果有错误,那么就是域名不同,parent.document.domain不可访问 parent.location.href="about:blank"; } </script> |