温馨提示×

温馨提示×

您好,登录后才能下订单哦!

密码登录×
登录注册×
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》

如何使用JavaScript中的try catch throw处理异常

发布时间:2022-03-28 11:29:05 来源:亿速云 阅读:266 作者:小新 栏目:web开发

这篇文章主要为大家展示了“如何使用JavaScript中的try catch throw处理异常”,内容简而易懂,条理清晰,希望能够帮助大家解决疑惑,下面让小编带领大家一起研究并学习一下“如何使用JavaScript中的try catch throw处理异常”这篇文章吧。

使用JavaScript中的try catch throw 处理异常

在JavaScript中定义异常;

(1)、EvalError: An error occurs in the eval() function.

(2)、RangeError: A number value is greater then or less then the number that can be represented in Javascript(Number.MAX_VALUE and Number.MIN_VAKUE).

(3)、ReferenceError: An illegal reference is used.

(4)、SyntaxError: A syntax error occus inside of an eval() function call. All other syntax error are reorted by the browser and cannot be handled with a try...catch statement.

(5)、TypeError. A variables type is unexpected. 6.URIError. An error ocuurs in the encodeURI() or the decodeURI() function.

代码如下如下所示:

<script type="text/javascript">  function CreateError()  {  throw new Error("Created error by custom.");  }  try  {  //throw a error from a function just want to see the call stack in firefox.  CreateError();  }  catch(error)  {  var errorMsg = ("Message: " + error.message + "\n");  if(typeof(error.stack)!=undefined)  {  //FF  errorMsg += ("Line Number: " + error.lineNumber + "\n");  errorMsg += ("File Name: " + error.fileName + "\n");  errorMsg += ("Stack Trace:\n" + error.stack + "\n");  }  else  {  //IE  errorMsg += ("Description: " + error.description + "\n");  errorMsg += ("Number: " + error.number + "\n");  }  alert(errorMsg);  }  finally  {  //alert("End try catch.message from finally block.");  }  </script>

而且在我们的代码中,Error.messageIEFireFox都支持的属性, 然而IE支持description 和 number属性。

 FF支持fileName lineNumber 和 stack 属性, 由于Javascript是弱类型的语言, 所以在catch部分只能catch一次,不能像C#这样的语言可以写多个catchcatch不同类型的exception。        但是可以用 instanceof ErrorType的方式实现类似的功能。代码如下所示:

<script type="text/javascript">  try  { //Syntax Error  //eval("alert a");  //Custom Error  throw new Error("An error occured.");  }  catch(error)  {  if(error instanceof SyntaxError)  {  alert("Syntax Error");  }  else if(error instanceof EvalError)  {  alert("Eval Error");  }  else if(error instanceof RangeError)  {  alert("Range Error");  }  else if(error instanceof ReferenceError)  {  alert("Reference Error");  }  else if(error instanceof TypeError)  {  alert("Type Error");  }  else if(error instanceof Error)  {  alert("Custon Error");  }  alert(error.message);  }  </script>

关于JavaScriptassert()这方面的话我们可以看下面这串代码:

function assert(bCondition, sErrorMsg) {     if (!bCondition) {        alert(sErrorMsg);        throw new Error(sErrorMsg);     }  }

以上是“如何使用JavaScript中的try catch throw处理异常”这篇文章的所有内容,感谢各位的阅读!相信大家都有了一定的了解,希望分享的内容对大家有所帮助,如果还想学习更多知识,欢迎关注亿速云行业资讯频道!

向AI问一下细节

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

AI