Results 1 to 30 of 31
Thread: C#: Exception handling(?)
-
29-07-2012, 02:29 AM #1
C#: Exception handling(?)
I have recently started learning C#. I was making a simple form application to calculate sum of fruits (checked through checkboxes) and quantity entered.
Problem is coming in quantity.
Exception is occuring in bold line when I'm running the program without entering any value textBox1 (quantity). Default value is 0. One thing is understood that exception is occuring due to the fact the compiler is in dilemma when it has to convert a blank value (" ") to an int which is rendering an exception. How to handle it?Code:if (Convert.ToInt32(textBox1.Text) > 0) { if (checkBox1.Checked) { qua1 = Convert.ToInt32(textBox1.Text); } else { MessageBox.Show("Please Check the respective items before entering values."); } } else { MessageBox.Show("Value of Quantity should be positive"); qua1 = 0; textBox1.Text = "0"; }
Another query. I have restricted entry of values in textBoxes to numerics only by using this-
But this is also blocking backspace to work, del is working though. I want backspace to work. My teacher told me a solution based on e.handled only but it was too complex for me too understand (its been few days since I started learning it).Code:private void textBox1_KeyPress_1(object sender, KeyPressEventArgs e) { e.Handled = !char.IsDigit(e.KeyChar); }
TIY
FAQ + answers for new members (Read before asking / messaging any moderator for any query)
Drop Box: Get 500MB free
Spoiler:
-
29-07-2012, 10:59 AM #2
Re: C#: Exception handling(?)
why not change if (Convert.ToInt32(textBox1.Text) > 0)
to if (textBox1.Text !="" && Convert.ToInt32(textBox1.Text) > 0)Twitter: twitter.com/SharmaTushar
Facebook: facebook.com/tushar.sharma
-
29-07-2012, 11:45 AM #3
Re: C#: Exception handling(?)
Change this
to something
if e.Handled is TRUE then the key press is mutedCode:private void textBox1_KeyPress(object sender, KeyPressEventArgs e) { bool isValidKey = char.IsDigit(e.KeyChar) || e.KeyChar == '\b'; e.Handled = !isValidKey; }
see ref. KeyPressEventArgs.Handled Property (System.Windows.Forms)There are more things in heaven and earth, Horatio,
Than are dreamt of in your philosophy.
-
29-07-2012, 01:48 PM #4
Re: C#: Exception handling(?)
You are doing things wrong and/or you got the basics wrong.
Convert.ToInt32() expects a number as a string (in the current overloaded form), An empty string is NOT a number, it's NOT null, it's just a string with length 0, i.e. an empty string. On the other hand "0", "1234", "65535" are numeric strings.
You might be confused since in C++, NULL was an int(0).
You should instead be handling the FormatException:
But looking closely you don't need Convert.ToInt32() since it's primarily used for much complex conversions from bytes, you can do away with just :Code:int value = 0; try{ value = Convert.ToInt32(value); } catch(FormatException){ MessageBox.show("Please enter only numbers", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error); }
or better, simply use:Code:int.Parse(value);
Code:int intVal; if(int.TryParse(value, out intVal)){ // intVal is initialized to either the value or 0 } else{ MessageBox.show("Please enter only numbers", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error); }
I remember doing a similar thing eons ago. What I learnt was it wasn't worth it using this validation approach. Using this way, you effectively block out numerous valid keys out of the textbox which are not numeric, eg: Backspace, Del, Home, Ctrl/Shift, +/-, etc.
The proper way is to just validate on form submit, or if you are hell bent upon a KeyEvent validation, might I suggest doing it like this (the way I did it long ago):
Code:private string _valid = ""; private void textBox1_TextChanged(object sender, EventArgs e) { int t; if (int.TryParse(this.textBox1.Text + "0", out t)) this._valid = this.textBox1.Text; else this.textBox1.Text = this._valid; }Last edited by nbaztec; 29-07-2012 at 02:08 PM.
AMD Phenom II X6 1055T|MSI 880GMA-E45|MSI 7770|2x2 Corsair DDR3 1333MHz|CM Elite 310|Corsair CX400W|DELL ST2320L
Myself @ nbaztec.co.in
Build Your Rig! (XBlade) @ nbaztec.co.in - Build Your Rig!
My Inner Artist @ nbaztec.co.in - Designs
-
30-07-2012, 01:03 PM #5
-
30-07-2012, 01:32 PM #6
Re: C#: Exception handling(?)
^I don't know JS.
FAQ + answers for new members (Read before asking / messaging any moderator for any query)
Drop Box: Get 500MB free
Spoiler:
-
30-07-2012, 01:34 PM #7
Re: C#: Exception handling(?)
^^ its a windows app
Sujay, when are you initiating the calculation?the cake is a lie
621311.251521
-
30-07-2012, 01:34 PM #8
Re: C#: Exception handling(?)
AMD Phenom II X6 1055T|MSI 880GMA-E45|MSI 7770|2x2 Corsair DDR3 1333MHz|CM Elite 310|Corsair CX400W|DELL ST2320L
Myself @ nbaztec.co.in
Build Your Rig! (XBlade) @ nbaztec.co.in - Build Your Rig!
My Inner Artist @ nbaztec.co.in - Designs
-
30-07-2012, 01:38 PM #9
Re: C#: Exception handling(?)
^Oops...my bad didn't saw the Messagebox
HTC One V | Nokia 5233 | Nikon D3100 | Apple Ipod Touch 4G | Sound Magic PL21 | Sound Magic ES18
-
30-07-2012, 01:42 PM #10
Re: C#: Exception handling(?)
When I press "OK" button.
Its WIP still, making changes as per above suggestions.Code:private void button1_Click(object sender, EventArgs e) { if (checkBox1.Checked) { if (textBox1.Text != "") { qua1 = Convert.ToInt32(textBox1.Text); } else { MessageBox.Show("Please enter a quantity"); } } else { if (Convert.ToInt32(textBox1.Text) > 0) { MessageBox.Show("Please check the respective items after entering the quantity"); } } textBox5.Text = Convert.ToString(rate_mango * qua1); if (checkBox2.Checked) { if (textBox2.Text != "") { qua1 = Convert.ToInt32(textBox2.Text); } else { MessageBox.Show("Please enter a quantity"); } } textBox6.Text = Convert.ToString(rate_pineapple * qua2); if (checkBox3.Checked) { if (textBox3.Text != "") { qua1 = Convert.ToInt32(textBox3.Text); } else { MessageBox.Show("Please enter a quantity"); } } textBox7.Text = Convert.ToString(rate_apple * qua3); if (checkBox4.Checked) { if (textBox4.Text != "") { qua1 = Convert.ToInt32(textBox4.Text); } else { MessageBox.Show("Please enter a quantity"); } } textBox8.Text = Convert.ToString(rate_banana * qua4); textBox9.Text = Convert.ToString(Convert.ToInt32(textBox5.Text) + Convert.ToInt32(textBox6.Text) + Convert.ToInt32(textBox7.Text) + Convert.ToInt32(textBox8.Text)); }FAQ + answers for new members (Read before asking / messaging any moderator for any query)
Drop Box: Get 500MB free
Spoiler:
-
30-07-2012, 02:00 PM #11
Re: C#: Exception handling(?)
AMD Phenom II X6 1055T|MSI 880GMA-E45|MSI 7770|2x2 Corsair DDR3 1333MHz|CM Elite 310|Corsair CX400W|DELL ST2320L
Myself @ nbaztec.co.in
Build Your Rig! (XBlade) @ nbaztec.co.in - Build Your Rig!
My Inner Artist @ nbaztec.co.in - Designs
-
30-07-2012, 02:17 PM #12
Re: C#: Exception handling(?)
Update: I have made some changes:
How is this approach ? Can some optimisation be done? One thing I want to do but not able to figure out the way.Code:if (checkBox1.Checked) { if (textBox1.Text != "") { qua1 = Convert.ToInt32(textBox1.Text); } else { MessageBox.Show("Please enter a quantity"); } } else { if (textBox1.Text != "") { if (Convert.ToInt32(textBox1.Text) > 0) { MessageBox.Show("Please check the respective boxes after entering the values"); } else { MessageBox.Show("Please check the fruits you want and enter the respective quantity"); } }
else
{
MessageBox.Show("Please check the fruits you want and enter the respective quantity");
}
I want that the if this else becomes true, it shouldn't do anything but just "skip" the scope (current if-else) and proceed towards calculation without showing any Mesage.Box. But not able to figure out how to make it skip it like that ?
Some more queries:
1) Why is if (textBox1.Text != "") working but if (textBox1.Text = "") is not? Error = Cannot implicitly convert type 'string' to 'bool'.
2) As razerbladeXtreme said to use if (textBox1.Text !="" && Convert.ToInt32(textBox1.Text) > 0), it works. But if I swap both the conditions and write like this if (Convert.ToInt32(textBox1.Text) > 0 && textBox1.Text !="" ), it gives error. I used to think that compiler checks both the conditions in such situations, but here its giving error if first condition is failing (Convert.ToInt32(textBox1.Text) > 0). Is this the way compiler behaves or am I missing something?
I thought to do it in starting then skipped it
It can help you:
Spoiler:FAQ + answers for new members (Read before asking / messaging any moderator for any query)
Drop Box: Get 500MB free
Spoiler:
-
30-07-2012, 02:25 PM #13
Re: C#: Exception handling(?)
Your flow of control can use plenty of optimization but I'm guessing this exercise is rather a simple once, so just let it be.How is this approach ? Can some optimisation be done? One thing I want to do but not able to figure out the way.
Don't quite get you.I want that the if this else becomes true, it shouldn't do anything but just "skip" the scope (current if-else) and proceed towards calculation without showing any Mesage.Box. But not able to figure out how to make it skip it like that ?
You're assigning the value not checking (use ==)1) Why is if (textBox1.Text != "") working but if (textBox1.Text = "") is not? Error = Cannot implicitly convert type 'string' to 'bool'.
This is called short-circuit evaluation, been around since the days of C (if not Pascal too).2) As razerbladeXtreme said to use if (textBox1.Text !="" && Convert.ToInt32(textBox1.Text) > 0), it works. But if swap both the conditions and write like this if (Convert.ToInt32(textBox1.Text) > 0 && textBox1.Text !="" ), it gives error. I used to think that compiler checks both the conditions in such situations, but here its giving error if first condition is failing (Convert.ToInt32(textBox1.Text) > 0). Is this the way compiler behaves or am I missing something?
Basically it says if the first expression evaluates to false in a logical AND then other expressions do not need to be checked, same goes for logical OR.
You need to work on some basics first, take this C example and fire it up to notice the differences.
Code:#include <stdio.h> int foo() { printf("foo"); return 0; } int bar() { printf("bar"); return 1; } int main() { foo() && bar(); // Says foo printf("\n"); bar() && foo(); // Says barfoo printf("\n"); foo() || bar(); // Says foobar printf("\n"); bar() || foo(); // Says bar printf("\n"); return 1; }AMD Phenom II X6 1055T|MSI 880GMA-E45|MSI 7770|2x2 Corsair DDR3 1333MHz|CM Elite 310|Corsair CX400W|DELL ST2320L
Myself @ nbaztec.co.in
Build Your Rig! (XBlade) @ nbaztec.co.in - Build Your Rig!
My Inner Artist @ nbaztec.co.in - Designs
-
30-07-2012, 02:41 PM #14
Re: C#: Exception handling(?)
first you need to do the validations separately.
Code:string Str = textBox1.Text.Trim(); int Num; bool isNum = Int32.TryParse(Str, out Num); if (!isNum) { MessageBox.Show("Please enter numeric only"); return; } else { //continue your program }the cake is a lie
621311.251521
-
30-07-2012, 02:59 PM #15
Re: C#: Exception handling(?)
Yeah
Originally Posted by nbaztec

For all textBoxes ?
Originally Posted by Charan
PS: Thanks to all for helping me
, especially nbaztec, you rock buddy 
What is Trim used for? (I can't understand it by explanation of intellisense.
)
Explain this line please:I mean what its doing? TryParse is for ?Code:bool isNum = Int32.TryParse(Str, out Num);
PS: I'm a newbie in this, so hold on your asses long please
FAQ + answers for new members (Read before asking / messaging any moderator for any query)
Drop Box: Get 500MB free
Spoiler:
-
30-07-2012, 03:05 PM #16
Re: C#: Exception handling(?)
Yes, for every textbox you need to do validation. or you can write a function to do this. ill give a sample soon.For all textBoxes ?
trim is used to remove white spaces from a stringWhat is Trim used for? (I can't understand it by explanation of intellisense.
)
Explain this line please:Code:bool isNum = Int32.TryParse(Str, out Num);
The TryParse method is like the Parse method, except the TryParse method does not throw an exception if the conversion fails. It eliminates the need to use exception handling to test for a FormatException in the event that s is invalid and cannot be successfully parsed.I mean what its doing? TryParse is for ?
if the string is a number then the statement will convert the string to numeric and place it in "Num" variable. it will then return "true" to isNum Variable.
incase the string is not a numeric then "Num" will have "null" and return value will be "false".
Int32.TryParse Method (String, Int32) (System)
EDIT: BTW .. the "out" keyword.. its like "ref" keyword, only thing is that "out" doesn't require the variable to be initialized.Last edited by RCuber; 30-07-2012 at 03:14 PM.
the cake is a lie
621311.251521
-
30-07-2012, 03:21 PM #17
Re: C#: Exception handling(?)
@dashing.sujay: can u post the scenario of validation u need when clicking submit button?
so we can optimise the code more.HTC One V | Nokia 5233 | Nikon D3100 | Apple Ipod Touch 4G | Sound Magic PL21 | Sound Magic ES18
-
30-07-2012, 03:37 PM #18
Re: C#: Exception handling(?)
I guess I am validating all the textboxes separately. All the validations are done on clicking "OK" button, or am I taking it wrong?
FAQ + answers for new members (Read before asking / messaging any moderator for any query)
Drop Box: Get 500MB free
Spoiler:
-
30-07-2012, 03:43 PM #19
Re: C#: Exception handling(?)
^^what you are doing is fine for a beginner. you need to learn the basic things your self.. once you are a little comfortable with the language, you can go ahead learning advanced techniques.
don't get worried if you are getting errors. try to check the flow once or twice before posting here.. we can help you without any problem,but that's not the point.. you need to learn about the issues which come up when you are coding.the cake is a lie
621311.251521
-
30-07-2012, 03:47 PM #20
Re: C#: Exception handling(?)
HTC One V | Nokia 5233 | Nikon D3100 | Apple Ipod Touch 4G | Sound Magic PL21 | Sound Magic ES18
-
30-07-2012, 04:02 PM #21
Re: C#: Exception handling(?)
FAQ + answers for new members (Read before asking / messaging any moderator for any query)
Drop Box: Get 500MB free
Spoiler:
-
30-07-2012, 04:06 PM #22
-
30-07-2012, 04:31 PM #23
Re: C#: Exception handling(?)
Welcome to world of c#.
So here are few code suggestions-
1.Always have some good naming conventions.This helps
to improve code readability
Eg-chkFruits,nMangoes,etc
2.You can use String.Empty instead of "" for readability
3.I think as you want to validate four times using same
logic.A functions will make code tidy.
Alternate way as per OOPS ideology
is creating a validation class for you objects
which is pretty high level for now.
Like
4.Remove {} for single statements of if.Code:public void ValidateControlandAssign(CheckBox targetChkbox,TextBox tValue,TextBox tAssign,int rate ) { private const string senterqty="Please enter a quantity"; private const string scheck="Please check the respective items after entering the quantity"); private int tempval; if (targetChkbox.Checked) { if (tValue.Text != String.Empty) tempval = Convert.ToInt32(tvalue); else MessageBox.Show(senterqty); } else { if (Convert.ToInt32(tValue.Text) > 0) MessageBox.Show(scheck); } tAssign.Text= = Convert.ToString(rate * tempval); } private void button1_Click(object sender, EventArgs e) { .. //as per your code call //observe how names of control of your code doesnt make sense except mango ValidateControlandAssign(checkBox1,textBox1,textBox5.Text, rate_mango); .. }
5.Dont hardcode strings.Put it in either config fileCode:if (true) singlestatment; else singlestatment;
or constants.
Spoiler:
6.You can also use
Int.TryParse for readability
-
30-07-2012, 05:06 PM #24Wise Old Owl
- Join Date
- Jul 2010
- Location
- Mumbai
- Posts
- 1,171
Re: C#: Exception handling(?)
Have not read the complete thread but seen this in condition statement
textBox1.Text != ""
Instead use this
http://stackoverflow.com/questions/6...itespacestringIsNullOrWhiteSpace or IsNullOrEmpty
String.IsNullOrWhiteSpace Method (System)Core-i5 2400 | Intel DH67BL | G.Skill 8GB DDR3 1333Mhz | 500GB Segate | CM 430 | Corsair VX550 PSU| BENQ V2410 eco LED Monitor | Genuine windows 7 64-bit Ultimate | Google Galaxy Nexus, Samsung Galaxy S & boring Nokia Lumia 800 :( , iPad 4
-
30-07-2012, 05:21 PM #25
Re: C#: Exception handling(?)
There is absolutely no need for checking String to be empty, the reason being there are only 2 equivalence classes - Correct Input and Incorrect Input and an empty string is the same as an incorrect numeric string.
@ds_
As I have earlier demonstrated the use of int.TryParse(), I suggest you instead use int.Parse() and handle the exception.
The most crude form of it would look like:
This way the calculation will cease once it detects one of the inputs as Invalid, I'd show you a much, much better way of handling things like these (using foreach and Controls property) but it'd be an overkill for now.Code:public void buttonOk_Click() { try { this.itemPrice1.Text = int.Parse(this.itemQty1.Text) * itemRate1; this.itemPrice2.Text = int.Parse(this.itemQty2.Text) * itemRate2; this.itemPrice3.Text = int.Parse(this.itemQty3.Text) * itemRate3; .... CalculateTotal(); } catch(FormatException) { MessageBox.Show("Only numbers are allowed") } }
P.S. There is no need for Trim() here since TryParse()/Parse() trims it anyway.AMD Phenom II X6 1055T|MSI 880GMA-E45|MSI 7770|2x2 Corsair DDR3 1333MHz|CM Elite 310|Corsair CX400W|DELL ST2320L
Myself @ nbaztec.co.in
Build Your Rig! (XBlade) @ nbaztec.co.in - Build Your Rig!
My Inner Artist @ nbaztec.co.in - Designs
-
30-07-2012, 07:14 PM #26
Re: C#: Exception handling(?)
Thanks for your inputs but what's your take on nbaztec's opposition for 2nd point.
Originally Posted by gopi_vbboy
PS: Your 3rd and 5th point bounced my head
@nbaztec: Working on it buddy
Any views for this: C# int.Parse Optimization
Ok, am almost done, one query.
When I write else like
it gives Possibly mistaken empty statement warning. (runs fine though)Code:else;
But when I write like:
It says fine.Code:else {}
Everything fine now. Final queries:
Code of OK (submit) button:
Spoiler:
Code of "Reset" button:
Spoiler:
1) The warning messages are coming as many times as error is occurred. Like if the user enters the value for all 4 items but forgets to check the respective boxes, it gives error 4 times. How do I make it once?
2) I do a sample calculation for the first time, then press "Reset" button. Then I press "OK" button without entering any values. This should give grand total = 0 but its giving last grand total. I'm not able to catch what's wrong. It was not happening earlier, but in the modification process something went wrong.
This screenie of my app may help you overcoming my bad naming convention.
Spoiler:
One more question:
I applied E.Handled restriction only to textBox1 but its working on all quantity textboxes (1-4). I can see it activated in properties, KeyPress event of all quantity textBoxes? How is it possible?FAQ + answers for new members (Read before asking / messaging any moderator for any query)
Drop Box: Get 500MB free
Spoiler:
-
30-07-2012, 10:06 PM #27
Re: C#: Exception handling(?)
It's optimization at the cost of error checking. It won't throw errors on invalid inputs like "12s2". It uses the age-old technique of converting ASCII numbers to decimal.
This is compiler check. It does it since programmers sometimes tend to misplace ';' like:
If it's bothering you, you can turn it off either by setting the compiler options via properties to /nowarn 642 or using the good old #pragma directive #pragma warning disable 642. Alternatively you can exclude that optional else clauseCode:if(condition); // Erroneous semi-colon doSomeWork();
Try the try-catch approach. If you don't want to do that, then use a boolean flag to set it as true if some error occured. Then display the error only once.1) The warning messages are coming as many times as error is occurred. Like if the user enters the value for all 4 items but forgets to check the respective boxes, it gives error 4 times. How do I make it once?
I'm guessing some errand variables you failed to reset.2) I do a sample calculation for the first time, then press "Reset" button. Then I press "OK" button without entering any values. This should give grand total = 0 but its giving last grand total. I'm not able to catch what's wrong. It was not happening earlier, but in the modification process something went wrong.
Possible if you copied-pasted those text-boxes from the first one.I applied E.Handled restriction only to textBox1 but its working on all quantity textboxes (1-4). I can see it activated in properties, KeyPress event of all quantity textBoxes? How is it possible?AMD Phenom II X6 1055T|MSI 880GMA-E45|MSI 7770|2x2 Corsair DDR3 1333MHz|CM Elite 310|Corsair CX400W|DELL ST2320L
Myself @ nbaztec.co.in
Build Your Rig! (XBlade) @ nbaztec.co.in - Build Your Rig!
My Inner Artist @ nbaztec.co.in - Designs
-
31-07-2012, 06:34 PM #28
Re: C#: Exception handling(?)
Do I really need that fuss? I just included the braces.If it's bothering you, you can turn it off either by setting the compiler options via properties to /nowarn 642 or using the good old #pragma directive #pragma warning disable 642. Alternatively you can exclude that optional else clause
What is try-catch approach ? I didn't got it at all.Try the try-catch approach. If you don't want to do that, then use a boolean flag to set it as true if some error occured. Then display the error only once.
There are total 8 variables. 4 for inputting quantity & 4 for rate. I already gave "rest" code in above post in which I reset all the textboxes and quantity variables. Rate is of course not required.I'm guessing some errand variables you failed to reset.
No, I didn't.Possible if you copied-pasted those text-boxes from the first one.
PS: thanks for all the help
FAQ + answers for new members (Read before asking / messaging any moderator for any query)
Drop Box: Get 500MB free
Spoiler:
-
31-07-2012, 07:06 PM #29
-
31-07-2012, 08:15 PM #30
Re: C#: Exception handling(?)
You can remove the else clause altogether, it's optional.
What is try-catch approach ? I didn't got it at all.Code:public void buttonOk_Click() { try { this.itemPrice1.Text = int.Parse(this.itemQty1.Text) * itemRate1; this.itemPrice2.Text = int.Parse(this.itemQty2.Text) * itemRate2; this.itemPrice3.Text = int.Parse(this.itemQty3.Text) * itemRate3; .... CalculateTotal(); } catch(FormatException) { MessageBox.Show("Only numbers are allowed") } }The code seems fine, but surely there's something incorrect in the code itself.There are total 8 variables. 4 for inputting quantity & 4 for rate. I already gave "rest" code in above post in which I reset all the textboxes and quantity variables. Rate is of course not required.
Or you selected all the boxes, but that's irrelevant. Just select all the textboxes and remove the definition, then put it for the correct textbox.No, I didn't.AMD Phenom II X6 1055T|MSI 880GMA-E45|MSI 7770|2x2 Corsair DDR3 1333MHz|CM Elite 310|Corsair CX400W|DELL ST2320L
Myself @ nbaztec.co.in
Build Your Rig! (XBlade) @ nbaztec.co.in - Build Your Rig!
My Inner Artist @ nbaztec.co.in - Designs
Similar Threads
-
Exception handling - Java
By amit dutt in forum ProgrammingReplies: 1Last Post: 25-09-2011, 03:04 AM -
I want GTA SA handling.cfg file.
By Gigacore in forum GamerzReplies: 2Last Post: 01-07-2008, 10:25 PM -
File handling using GCC/G++
By anantkhaitan in forum ProgrammingReplies: 16Last Post: 22-05-2007, 04:19 PM -
File handling using GCC/G++
By anantkhaitan in forum QnA (read only)Replies: 16Last Post: 22-05-2007, 04:19 PM -
Handling /dev/dsp in C
By desertwind in forum Open SourceReplies: 1Last Post: 04-01-2007, 07:32 PM



LinkBack URL
About LinkBacks
Reply With Quote

Bookmarks