【问题标题】:Is it okay to throw Exception in try catch block depending on if condition to stop executing try block and start executing catch block?是否可以根据 if 条件在 try catch 块中抛出异常以停止执行 try 块并开始执行 catch 块?
【发布时间】:2020-12-11 00:42:04
【问题描述】:

例子

try {
      let items = JSON.parse(localStorage.getItem('items'))
      if(items.length === 0){
          throw new Exception()    
      }
      // other code
      fetch('http://localhost:9004/merge-items').then(...)
}catch(e){
      console.error(e)
      fetch('http://localhost:9004/load-items').then(...)
}

我在 if 块内抛出异常,因为我需要编写与 catch 块内类似的代码

try {
      let items = JSON.parse(localStorage.getItem('items'))
      if(items.length === 0){
           fetch('http://localhost:9004/load-items').then(...)   // The same code
      }
      // other code
      fetch('http://localhost:9004/merge-items').then(...)
}catch(e){
      console.error(e)
      fetch('http://localhost:9004/load-items').then(...) // The same code
}

【问题讨论】:

标签: javascript exception try-catch


【解决方案1】:

如果你只问是否可以,那么“不”,就不行了。

您可以将异常视为您不期望的事情,但您可以预测。在您期望的代码中,有时(一开始?)您的本地存储项目可能是空的。

所以,更好:

const loadItems = () => {
  fetch('http://localhost:9004/load-items').then(...)   // The same code
}

try {
  let items = JSON.parse(localStorage.getItem('items'))
  if (items.length === 0) {
    loadItems();
  }
  // other code
  fetch('http://localhost:9004/merge-items').then(...)
} catch (e) {
  console.error(e)
  loadItems();
}

【讨论】:

  • 好的,但是为什么要在 catch 块中执行 loadItems() 呢?还是在 catch 块中获取原始问题中的项目?您已经检查了本地内存中是否没有项目。
  • @Karlan 因为主题启动器说:“因为我需要编写与 catch 块内类似的代码”。我不知道他为什么需要这个。
猜你喜欢
  • 2021-11-17
  • 2017-01-30
  • 2011-03-18
  • 1970-01-01
  • 1970-01-01
  • 2011-03-25
  • 1970-01-01
  • 1970-01-01
  • 2012-02-20
相关资源
最近更新 更多