简体   繁体   English

如何在我的计算器中实现 try 和 catch 以防止错误?

[英]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.

相关问题 帮助解决我在计算器中实现 try catch 的问题 - Assistance for my problem with my try catch implementation in calculator try-catch是否意味着防止或处理错误? (在javascript中) - Is try-catch meant to prevent or handle errors? (in javascript) 如何使用try catch捕获Javascript中的函数错误? - How to use try catch for function errors in Javascript? 如何处理 try/catch 之外的错误? - How to handle errors outside try/catch? 如何处理 rxjs 而不是 try/catch 中的错误? - How to handle errors in rxjs instead of try/catch? 如何在不尝试捕获的情况下全局捕获 JavaScript 错误 - How to catch JavaScript errors globally without try catch 如何使用低阶函数的 try catch 捕获错误 - How catch Errors with try catch of lower order functions 如何在没有try / catch的情况下捕获错误,或者在运行时使用try / catch打包代码? - How to catch errors without try/catch OR wrap code with try/catch in runtime? 尝试/捕获并不能防止崩溃 - Try/Catch does not prevent crash 在try ... catch javascript / nodejs中,如何防止双重回调? - How to prevent double callbacks during try…catch in javascript / nodejs?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM