我是 C++ 编程新手,但已经使用高级语言进行编程,可以找到解决大多数文档的方法。我正在学习 C++ 中的异常处理,特别是通过以下示例:
vector<int> myNums;
try
{
myNums.resize(myNums.max_size() + 1);
}
catch (const bad_alloc& err)
{
cout << err.what() << endl;
}
Run Code Online (Sandbox Code Playgroud)
此代码不会捕获异常,因为 .resize() 方法抛出的异常不是bad_alloc
;它是length_error
。那么,从这个文档中,您如何实现这一点呢?也许我错过了一些明显的事情。
https://cplusplus.com/reference/vector/vector/resize/
其中提到的唯一具体例外是bad_alloc
. 有人可以告诉我如何从该页面开始知道这length_error
是正确的例外吗?
我的代码导致意外数量的重新渲染.
function App() {
const [isOn, setIsOn] = useState(false)
const [timer, setTimer] = useState(0)
console.log('re-rendered', timer)
useEffect(() => {
let interval
if (isOn) {
interval = setInterval(() => setTimer(timer + 1), 1000)
}
return () => clearInterval(interval)
}, [isOn])
return (
<div>
{timer}
{!isOn && (
<button type="button" onClick={() => setIsOn(true)}>
Start
</button>
)}
{isOn && (
<button type="button" onClick={() => setIsOn(false)}>
Stop
</button>
)}
</div>
);
}
Run Code Online (Sandbox Code Playgroud)
请注意第4行的console.log.我期望以下内容被注销:
重新渲染0
重新渲染0
重新渲染1
第一个日志用于初始渲染.当"isOn"状态通过按钮单击更改时,第二个日志用于重新呈现.第三个日志是setInterval调用setTimer时,它会再次重新渲染.这是我实际得到的:
重新渲染0
重新渲染0
重新渲染1
重新渲染1
我无法弄清楚为什么会有第四个日志.这是一个链接到它的REPL:
https://codesandbox.io/s/kx393n58r7
***只是为了澄清,我知道解决方案是使用setTimer(timer …