Using a try block
Furthermore, because there's no guarantee that the input from the user can be successfully converted, depending on what somebody enters, you have to type try
directly below the double x,y;
declaration statement, as follows:
double x, y;// variables for reading input try
You can put any stuff that is to be tried, but not guaranteed, to be successful within a try
block.
Now enter the following between curly braces directly below try
:
x = Convert.ToDouble(TextBox1.Text); y = Convert.ToDouble(TextBox2.Text);
Throwing an exception
For the next stage, enter the following directly below the lines of code mentioned in the preceding section. But this stage could generate errors. This is because if y
is zero, then it is not allowed in mathematics. So, next what we'll do is also type the following:
if (y == 0) { throw new DivideByZeroException(); }
What is this? DivideByZeroException
is a class. If you hover your mouse over this class, the pop-up tooltip says this: Initializes a new instance...