How to display alert after Eval() error?

Asked

Viewed 72 times

3

I have a calculator that works more or less like this:

[bolas][+][preco da bola]

I see the string replacing [XXXXXXX] with the corresponding value and use Eval to perform the calculation. But there may be cases of error when for example the calculation gets like this:

eval("5 + [preco da bola]");
  • The JS code stops when this error occurs?
  • If the code stops I have a way to prevent it from running?
  • I can detect the error and send a custom Alert?

2 answers

2


Would that be?....

try{
    eval("5 + [preco da bola]");
}catch(e){
    console.log(e);
}

2

You can always make a mistake by not crossing over to the client’s side with:

try{
    // o código que pode dar erro aqui
}
catch(erro){
    // este codigo é corrido quando houver erros. A variável "erro" contêm o código do erro
}

I think it would be more interesting to do it without Val, if you want help you have to give more details.

  • because if I put 5 + [xxx] without Eval javascript does not take to Cacth?

  • 1

    @Joaopaulo makes a jsFiddle to help better. Otherwise I’ll be guessing what you want. 5 + [xxx] makes a mistake of parse, not a mistake in Runtime.

  • I think that your comment already responds. Parse errors can not prevent then ne?

  • 1

    @Exact Joaopaulo. This gives error even before the script runs.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.