Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[js] 第81天 在js中怎么捕获异常?写出来看看?应该在哪些场景下采用呢? #578

Open
haizhilin2013 opened this issue Jul 5, 2019 · 5 comments
Labels
js JavaScript

Comments

@haizhilin2013
Copy link
Collaborator

第81天 在js中怎么捕获异常?写出来看看?应该在哪些场景下采用呢?

@haizhilin2013 haizhilin2013 added the js JavaScript label Jul 5, 2019
@ghost
Copy link

ghost commented Jul 6, 2019

try {
    ...
    throw ...
    ...
} catch (err) {
    ...
} finally {
    ...
}
  • 通过 throw 语句抛出错误;理论上可以抛一切值,但实际上建议只抛 Error 对象;
  • try 块内 throw 的错误会导致停止执行,并将抛出的对象传给 catch 块;
    • 从 ES2017 开始,如果不需要获取抛出的对象,则 catch 块 可以直接写为 catch { ... }
  • catch 块一般用于对错误进行处理;
  • finally 块中的语句不论是否抛出错误,都会执行。

该在什么场景下用?所有你不想让用户接手的错误处理都应该用。

@HCLQ
Copy link

HCLQ commented Jul 6, 2019

window.onerror = function(message, source, lineno, colno, error) { ... } 可以在全局顶层监听未捕获的错误
window.addEventListener('unhandledrejection', event => ···);监听未捕捉的promise错误

@imccode
Copy link

imccode commented Jul 9, 2019

通常在以下几点使用:

  • 复杂逻辑代码库
  • 发起 ajax、fetch 的时候
  • 判断是否支持默写浏览器特性
        async function requestData() {
          try {
            if (this.loading) return
            this.loading = true

            await api.getData()

            ...
          } catch (err) {
            console.error(err)
          } finally {
            this.loading = false
          }
        }

@songlovena
Copy link

(1) js在运行过程中,一旦发生错误,程序就中止执行了;这极大的影响了用户体验。
js提供了 try...catch结构,对错误进行收集,并让程序继续向下执行。

(2) 注意:语法错误无效,比如输入变量时多写了符合:等

(3) try...catch结构允许在最后添加一个finally代码块,表示不管是否出现错误,都会执行其内部的代码。

(4) 使用场景很多,只要是任何你认为可能报错的地方时都可以使用try...catch结构;比如:开发小程序,同步获取用户手机信息时,判断浏览器是否支持XMLHttpRequest对象时等

try{
  throw new Error('err');
}catch(e){
  console.log(e)
}

@xiaoqiangz
Copy link

一般都是
try{
}catch(){
}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
js JavaScript
Projects
None yet
Development

No branches or pull requests

5 participants