TECHNOLOGIES
FORUMS
JOBS
BOOKS
EVENTS
INTERVIEWS
Live
MORE
LEARN
Training
CAREER
MEMBERS
VIDEOS
NEWS
BLOGS
Sign Up
Login
No unread comment.
View All Comments
No unread message.
View All Messages
No unread notification.
View All Notifications
Answers
Post
An Article
A Blog
A News
A Video
An EBook
An Interview Question
Ask Question
Forums
Monthly Leaders
Forum guidelines
Doane Hopkins
NA
3
0
Problems with try, catch blocks.
Nov 20 2008 2:17 PM
Having a problem with exception handling. I created a form with 5 textboxes. The first four are for the user to enter the coordinates of two points and the fifth displays the length of a line between the two when clicking button1.
This code compiles.
private void button1_Click(object sender, EventArgs e)
{
string startingX;
string startingY;
string endingX;
string endingY;
double line;
string length;
startingX = textBox1x.Text;
startingY = textBox1y.Text;
endingX = textBox2x.Text;
endingY = textBox2y.Text;
double startX = double.Parse(startingX);
double startY = double.Parse(startingY);
double endX = double.Parse(endingX);
double endY = double.Parse(endingY);
line = Math.Sqrt(
(endX - startX) * (endX - startX) + (endY - startY) * (endY - startY));
length = line.ToString();
textBoxline.Text = length;
When I try to handle exceptions with try, catch in the code below this gives errors on the line = Math.Sqrt operation saying that my end and start variables do not exist in the current context. I tried wrapping all four parse lines in a single block and got the same errors. I just can't seem to get my mind around exceptions. Any help would be greatly appreciated.
private void button1_Click(object sender, EventArgs e)
{
string startingX;
string startingY;
string endingX;
string endingY;
double line;
string length;
startingX = textBox1x.Text;
startingY = textBox1y.Text;
endingX = textBox2x.Text;
endingY = textBox2y.Text;
try
{
double startX = double.Parse(startingX);
}
catch (FormatException)
{
MessageBox.Show("Please enter a valid integer for the first points X coordinate!");
}
try
{
double startY = double.Parse(startingY);
}
catch (FormatException)
{
MessageBox.Show("Please enter a valid integer for the first points Y coordinate!");
}
try
{
double endX = double.Parse(endingX);
}
catch (FormatException)
{
MessageBox.Show("Please enter a valid integer for the second points X coordinate!");
}
try
{
double endY = double.Parse(endingY);
}
catch (FormatException)
{
MessageBox.Show("Please enter a valid integer for the second points Y coordinate!");
}
line = Math.Sqrt(
(endX - startX) * (endX - startX) + (endY - startY) * (endY - startY));
length = line.ToString();
textBoxline.Text = length;
Reply
Answers (
2
)
Import Windows Forms into MonoDev Stetic Designer
Help me to compare 2 images with each other.