最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - "Try...Catch" Block not Working with parseInt() - Stack Overflow

programmeradmin0浏览0评论

What I'm trying to do:

I have a javascript program that, when a button is clicked, takes in 4 strings from 4 text boxes in a form, and outputs those strings into a formatted textarea.

function testResults(form){
var errorhandle1 = parseInt(document.myForm.Item_Code.value);
var errorhandle2 = parseInt(document.myForm.Item_Cost.value);
var errorhandle3 = parseInt(document.myForm.Quantity.value);
//above variables are for error handling.
var d = "   ";
var subtotal = parseInt(form.Item_Cost.value) * parseInt(form.Quantity.value);
var subtotalValue = parseInt(document.myForm.Subtotal.value);
var testVar = "Item Code: " + form.Item_Code.value + d + 
              "Item Name: " + form.Item_Name.value + d + 
              "Item Cost: " + form.Item_Cost.value + d + 
              "Quantity: " + form.Quantity.value + '\n';


document.myForm.myTextarea.value += testVar;
document.myForm.Subtotal.value = parseInt(subtotal) + subtotalValue;
document.myForm.Sales_Tax.value =  document.myForm.Subtotal.value * salestax;
document.myForm.Total.value = parseInt(document.myForm.Subtotal.value) + parseFloat(document.myForm.Sales_Tax.value);
}

The above code works just fine, and does exactly what I want it to do for the scope of my program.

try {
    if ((isNaN(errorhandle3) == true) || (isNaN(errorhandle2) == true)) {
        throw "Error1";
    }
} catch (e) {
    if (e == "Error1") {
        alert("Error! You must enter a number into the qty and cost fields!");
    }
}

What I'm trying to accomplish with the try...catch block is simply to make sure that

document.myForm.Item_Code.value
document.myForm.Item_Cost.value
document.myForm.Quantity.value

are actually numbers.

The try...catch statements trigger every time I run the program and doesn't care what I put in the corresponding text boxes. I would greatly appreciate any and all insight on this!

Also: I looked at both of these links and was unable to understand my problem. javascript parseInt return NaN for empty string .asp

What I'm trying to do:

I have a javascript program that, when a button is clicked, takes in 4 strings from 4 text boxes in a form, and outputs those strings into a formatted textarea.

function testResults(form){
var errorhandle1 = parseInt(document.myForm.Item_Code.value);
var errorhandle2 = parseInt(document.myForm.Item_Cost.value);
var errorhandle3 = parseInt(document.myForm.Quantity.value);
//above variables are for error handling.
var d = "   ";
var subtotal = parseInt(form.Item_Cost.value) * parseInt(form.Quantity.value);
var subtotalValue = parseInt(document.myForm.Subtotal.value);
var testVar = "Item Code: " + form.Item_Code.value + d + 
              "Item Name: " + form.Item_Name.value + d + 
              "Item Cost: " + form.Item_Cost.value + d + 
              "Quantity: " + form.Quantity.value + '\n';


document.myForm.myTextarea.value += testVar;
document.myForm.Subtotal.value = parseInt(subtotal) + subtotalValue;
document.myForm.Sales_Tax.value =  document.myForm.Subtotal.value * salestax;
document.myForm.Total.value = parseInt(document.myForm.Subtotal.value) + parseFloat(document.myForm.Sales_Tax.value);
}

The above code works just fine, and does exactly what I want it to do for the scope of my program.

try {
    if ((isNaN(errorhandle3) == true) || (isNaN(errorhandle2) == true)) {
        throw "Error1";
    }
} catch (e) {
    if (e == "Error1") {
        alert("Error! You must enter a number into the qty and cost fields!");
    }
}

What I'm trying to accomplish with the try...catch block is simply to make sure that

document.myForm.Item_Code.value
document.myForm.Item_Cost.value
document.myForm.Quantity.value

are actually numbers.

The try...catch statements trigger every time I run the program and doesn't care what I put in the corresponding text boxes. I would greatly appreciate any and all insight on this!

Also: I looked at both of these links and was unable to understand my problem. javascript parseInt return NaN for empty string http://www.w3schools.com/jsref/jsref_isnan.asp

Share Improve this question edited May 23, 2017 at 12:32 CommunityBot 11 silver badge asked Dec 4, 2014 at 1:52 FishbonesFishbones 1031 gold badge1 silver badge4 bronze badges 3
  • 4 This makes no sense here to use try/catch around something this simple that doesn't by itself throw. You can just use a straight if statement and the code will be simpler and perform better. I don't see any need for exceptions here. – jfriend00 Commented Dec 4, 2014 at 1:56
  • 2 Tip: don’t test booleans against == true. It’s redundant; if (isNaN(errorhandle3) || isNaN(errorhandle2)) reads better. – Ry- Commented Dec 4, 2014 at 2:00
  • Thank you both for the quick reply. I'm in the process of changing those now. – Fishbones Commented Dec 4, 2014 at 2:09
Add a comment  | 

3 Answers 3

Reset to default 15

Your root problem here is that isNaN() tests to see if the value is NaN. It does not test to see if a string is a proper number. It has some coercion rules to try to deal with strings, but that really isn't what it is designed for.

You can see ways to test if something can be parsed into a valid number here: Validate decimal numbers in JavaScript - IsNumeric()

It's worth reading the detail in the good answers there, but it boils down to something like this which is a bit more than you need, but is general purpose:

function isNumber(n) {
  return !isNaN(parseFloat(n)) && isFinite(n);
}

And, then there's no reason to use exceptions in your code, so you can just do this:

if (!isNumber(errorhandle3) || !(isNumber(errorhandle2)) {
   alert("Error! You must enter a number into the qty and cost fields!");
}

Also, in your code, some .Value properties look like maybe they should be .value (lowercase).

Both parseInt() and isNaN() do not throw exceptions in JavaScript. They return NaN when the conversion fails, but they don't trigger a try-catch block naturally.

If you want exception while converting string to int you can use JSON.Parse

function main() {
  const S = readLine(); // Your number coming as a string.

  try {
    const convertedNum = JSON.parse(S);

    console.log(convertedNum);
  } catch (error) {
    console.log("Bad String");
  }
}

In your first code block

var errorhandle2 = parseInt(document.myForm.Item_Cost.Value);
var errorhandle3 = parseInt(document.myForm.Quantity.Value);

You are using Value, which should be value, that's case-sensitive.

By the way, isNaN returns boolean, you don't have to compare with true

发布评论

评论列表(0)

  1. 暂无评论