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>
"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.
– bfavaretto
@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".– Maniero
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 conditionif (inp == 0) {
second conditionif (inp < 1 || inp > 4) {
In that case if you enter the value0
and putalert
in both conditions will appear twice, one for each case. Withthrow
for in the first condition.– user60252
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.
– Maniero
ball show teacher!!
– user60252