What’s the difference between throw and Alert

Asked

Viewed 334 times

11

In the functions below I see that throw works the same as Alert. Can I replace it with an Alert? There would be some inconvenience?

var letters = new Array("A","B","C","D","E")
function getLetter(fld) {
     try {
           var inp = parseInt(fld.value, 10)
               if (isNaN(inp)) {
                    throw "Entry was not a number."
               }
               if (inp < 0 || inp > 4) {
                   throw "Enter only 0 through 4."
               }
               fld.form.output.value = letters[inp]
     }
     catch (e)  {
               alert(e)
               fld.form.output.value = ""
               fld.focus()
               fld.select()
     }
}
<FORM>
Enter a number from 0 to 4: 
<INPUT TYPE="text" NAME="input" SIZE=5>
<INPUT TYPE="button" VALUE="Get Letter" onClick=getLetter(this.form.input)>
Matching Letter is:<INPUT TYPE="text" NAME="output" SIZE=5>
</FORM>

To better understand my doubt I make the same code with alert and it works the same way: to verify type a non-numeric input in both codes

var letters = new Array("A","B","C","D","E")
function getLetter(fld) {
     try {
           var inp = parseInt(fld.value, 10)
               if (isNaN(inp)) {
                    alert("Entry was not a number.")
               }
               if (inp < 0 || inp > 4) {
                   throw "Enter only 0 through 4."
               }
               fld.form.output.value = letters[inp]
     }
     catch (e)  {
               alert(e)
               fld.form.output.value = ""
               fld.focus()
               fld.select()
     }
}
<FORM>
Enter a number from 0 to 4: 
<INPUT TYPE="text" NAME="input" SIZE=5>
<INPUT TYPE="button" VALUE="Get Letter" onClick=getLetter(this.form.input)>
Matching Letter is:<INPUT TYPE="text" NAME="output" SIZE=5>
</FORM>

3 answers

13


It just happens to behave the same way in this particular code. In fact this is not even required, and in fact Javascript not used in a browser will change for sure. There is zero relationship between them.

The alert() is a function present in the browser to alert something something and this is the only capability of it. It is something of the library and has no major consequences on the execution of the code.

The throw is something of the language, strongly interferes in the execution of the code and deviates its execution. It reminds a little return because he closes the execution there and stops at the first catch that he finds. He is a flow control command, but it should not be used for this. It is useful in some cases to report error to another unknown part of the code. When well used it can make the code easier to write and handle, if abused it can get much worse. It is a goto glorified, therefore very bad, unless it has a strong reason for its use that compensates for the problem it brings.

Almost always have a throw directly where there is a catch is a mistake. So in this case it makes no sense to do this, it is clearly a case to solve in the if.

I understand that this was just an example, but since you are in doubt of its use remember that it is useless in real code.

And to tell you the truth JS doesn’t have much of a culture of making exceptions, it turns out to be good, because people think it’s cute and abuse its use. There is a lot of material on the site on the subject.

See that if I take the alert() of catch doesn’t do the same thing.

var letters = new Array("A","B","C","D","E")
function getLetter(fld) {
    try {
        var inp = parseInt(fld.value, 10)
        if (isNaN(inp)) throw "Entry was not a number."
        if (inp < 0 || inp > 4) throw "Enter only 0 through 4."
        fld.form.output.value = letters[inp]
     } catch (e) {
        console.log("deu erro");
     }
}
<FORM>
Enter a number from 0 to 4: 
<INPUT TYPE="text" NAME="input" SIZE=5>
<INPUT TYPE="button" VALUE="Get Letter" onClick=getLetter(this.form.input)>
Matching Letter is:<INPUT TYPE="text" NAME="output" SIZE=5>
</FORM>

I put in the Github for future reference.

And now without the catch:

var letters = new Array("A","B","C","D","E")
function getLetter(fld) {
    var inp = parseInt(fld.value, 10)
    if (isNaN(inp)) throw "Entry was not a number."
    if (inp < 0 || inp > 4) throw "Enter only 0 through 4."
    fld.form.output.value = letters[inp]
}
<FORM>
Enter a number from 0 to 4: 
<INPUT TYPE="text" NAME="input" SIZE=5>
<INPUT TYPE="button" VALUE="Get Letter" onClick=getLetter(this.form.input)>
Matching Letter is:<INPUT TYPE="text" NAME="output" SIZE=5>
</FORM>

I put in the Github for future reference.

So there’s no way to establish any relationship between these two things.

As I anticipated is not much used in JS and so has little material, but can see on exceptions in other languages that is very similar:

  • 2

    "people think it’s cute and abuse its use". You’re right. I think it’s cute, but I avoid not knowing how to use it well enough.

  • 2

    @bfavaretto almost no one knows, including me :D But of course I know that he is problematic, is a goto in the worst way, you don’t even know where you’re going. I even have a talk called "Exceptions: the 21st century goto".

  • I get it, O throw é algo da linguagem, interfere fortemente na execução do código e desvia sua execução I did the following test: first condition if (inp == 0) { second condition if (inp < 1 || inp > 4) { In that case if you enter the value 0 and put alert in both conditions will appear twice, one for each case. With throw for in the first condition.

  • Yeah, it changes the flow. But there are several ways to do this, the exception should not be used to control the flow but rather facilitate when the flow is complex.

  • ball show teacher!!

10

In fact the statement throw doesn’t work the same at the alert, what it does is to cast a user-defined exception, and all it has after the throw will not be executed. And the control will be passed to the first block catch. In your case you have a block catch and in it you call the method alert passing the parameter e which is the exception you launched using the throw.

If you go on your block catch and comment on the method alert will see that no dialog box will be opened.

7

Actually what happens is this:

  • the throw throws an error
  • this error is caught by catch
  • the catch flame alert(e)

Example:

try {
    throw "erro!";
} catch(e) {
    alert(e);
}

Will be shown the alert with the error message.

But that doesn’t mean that the throw works the same as alert. Just remove the alert from within the catch to verify this:

try {
    throw "erro!";
} catch(e) {
    console.log(e);
}

Now the error message is shown in console, because I’m no longer calling the alert within the catch (I traded for console.log).

Notice that none alert was shown, therefore throw does not work the same as alert. He only throws the error (which will be captured by catch).


Your second example is just calling a alert within the try. As no error is generated in this case, it does not enter the catch:

try {
    alert("Entry was not a number.")
} catch(e) {
    alert("Não serei executado");
}


In short, the throw only throws error, which will be captured by catch. In your first example, try removing alert that’s inside the catch to see that no window of alert will be shown.

Browser other questions tagged

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