【问题标题】:how can I re-write the code by using try, throw, catch and finally to handle the errors?如何通过使用 try、throw、catch 和 finally 来处理错误来重写代码?
【发布时间】:2019-09-10 02:45:03
【问题描述】:

这实际上是一个功能齐全的代码(如果有人想使用)。我的问题是如何通过使用 try..catch..throw..finally 语法来处理错误来重写代码

  $(document).ready(function () {
     $(".submit").click(function (event){
        event.preventDefault()

        var email = $(".email").val()
        var subject = $(".subject").val()
        var statusElm = $(".status")
        statusElm.empty()

        if(email.length > 5 && email.includes("@") && email.includes(".")) {
    statusElm.append("<div>valid email</div>")
        }else{
    statusElm.append("<div>invalid email</div>")
        }

        if(subject.length > 2) {
    statusElm.append("<div>Valid Subject</div>")
        }else{
    statusElm.append("<div>invalid subject</div>")
        }
    })
})

更新: 我想出了这样的东西;

      $(document).ready(function () {
    $(".submit").click(function (event){
        event.preventDefault()

        var email = $(".email").val()
        var subject = $(".subject").val()
        var statusElm = $(".status")
        statusElm.empty()


  try { 
    if(email.length > 5 && email.includes("@") && email.includes("."))  throw "is not an email";
    if(subject.length > 2) throw "is not long enough";

  }
  catch(err) {
    status.innerHTML = "Input " + err;
   }
    })
  })

但它没有执行。我不知道如何使它工作。

【问题讨论】:

  • 我更喜欢你的原始代码。 :)

标签: javascript try-catch throw finally


【解决方案1】:

您只能在代码实际抛出错误时使用try/catch/throw/finally 实际。你可以在try 中抛出你自己的错误,但这会违背目的。

【讨论】:

  • 我想为此使用用户输入。
【解决方案2】:

我为 try 创建了另一个函数,并在不同的 JS 文件中捕获部分,所以一切都很好。只是想让大家知道。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2017-09-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-07-07
    • 2023-01-10
    相关资源
    最近更新 更多