[英]How to implement try and catch in my calculator to prevent errors?
If my input is 6++ I'm getting 6++ as the output, rather I want an 'err' in the output. How can I implement try and catch in my code to throw the error?如果我的输入是 6++,我将得到 6++ 作为 output,而我想要 output 中的“错误”。如何在我的代码中实现 try 和 catch 以抛出错误? ex inputs: 6++ output: err, input: 5+-3 output: err, etc. ex 输入:6++ output:错误,输入:5+-3 output:错误,等等。
Here's my code:这是我的代码:
let string = ""; let buttons = document.querySelectorAll('.button'); Array.from(buttons).forEach((button) => { button.addEventListener('click', (e) => { if (e.target.innerHTML == '=') { string = eval(string); document.querySelector('input').value = string; } else if (e.target.innerHTML == 'C') { string = " "; document.querySelector('input').value = string; } else { console.log(e.target) string = string + e.target.innerHTML; document.querySelector('input').value = string; } }) })
Simply put try
and catch
around the code that calls eval()
.只需围绕调用eval()
的代码放置try
and catch
即可。
Note that 5+-3
is perfectly fine in JavaScript, it's equivalent to 5-3
, so you won't get an error for that.请注意, 5+-3
在 JavaScript 中完全没问题,它等效于5-3
,因此您不会收到错误。
let string = ""; let buttons = document.querySelectorAll('.button'); Array.from(buttons).forEach((button) => { button.addEventListener('click', (e) => { if (e.target.innerHTML == '=') { try { string = eval(string); document.querySelector('input').value = string; } catch (e) { document.querySelector('input').value = "error: " + e; } } else if (e.target.innerHTML == 'C') { string = " "; document.querySelector('input').value = string; } else { console.log(e.target) string = string + e.target.innerHTML; document.querySelector('input').value = string; } }) })
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.