Jump to content

try-catch

- - - - -

This topic has been archived. This means that you cannot reply to this topic.
1 reply to this topic

#1
001

001

    Newbie

  • Members
  • Pip
  • 4 posts
hello readers,
i have one problem with my try-catch program. the problem is that i don't want to write down what the two numbers are, i want the program to automatically pick up the numbers and see the errors. this program is part of another program which my tutor gave but i can't get my head around it.


using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace Try_Cctch
{
class Program
{
static void Main(string[] args)
{
double exp1;
double exp2;
double result ;
Boolean OK = true;

do
{
try
{

Console.WriteLine("Enter the first number >");
exp1 = double.Parse(Console.ReadLine());
Console.WriteLine("Enter the second number >");
exp2 = double.Parse(Console.ReadLine());

result = exp1 / exp2;
Console.Write("accepted - the result of " + exp1 + "/" + exp2 + "= " + result);
OK = false;
}
catch (Exception ex)
{
string message = ex.Message;
Console.WriteLine(message + " an error occurred");
OK = true;
}
} while (OK != false);
Console.ReadLine();
}
}
}

#2
Davide

Davide

    Programming God

  • Members
  • PipPipPipPipPipPipPip
  • 506 posts
The program will return an error only if the user input will not be parsed corectly (ex. if you type "two" instead of "2" you will not be able to parse it).

Also, you must turn the double to a string to write it to the console window:
//Wrong
Console.Write("accepted - the result of " + exp1 + "/" + exp2 + "= " +  result);
//Right
Console.Write("accepted - the result of " + exp1.ToString() + "/" + exp2.ToString() + "= " +  result.ToString());
Please tell us the errors or what you can't do instead of just pasting the code.
Are you a newbie programmer trying to learn C#? Check out my small tutorial: Visual C# Programming Basics