Saturday, May 4, 2013

C# Basics: Arithmetic and Exceptions

Greetings!

Yesterday's article, C# Basics: Fun with Integers, introduced the integer data type, and showed that bad things happen if you try to convert a piece of non-numeric text (String) to an integer. But how do we handle such a situation? Today's article explains exactly that, and introduces other arithmetic operations that you can do with numbers.

Start off by creating a new console application in SharpDevelop or Visual Studio. If you don't remember how to do so, check my first article, C# Basics: Input and Output. Once you've done that, replace the sample code with the following:

int x = 5;
int y = 0;
int z = x / y;

Console.Write("Press any key to continue . . . ");

In this example, we are declaring two integer variables, x and y, dividing one by the other (/ means divided by), and storing the result in a third integer, z. This time we have no user interaction. But if you think that makes this a dull example, press F5 and see what happens...

BOOM. Basically, if you have a background in mathematics, you'll know that you should never divide by zero (as we've just done). If you don't, you should know that only Chuck Norris may divide by zero. You can't.

Chuck Norris doesn't allow programs to divide by zero either, so this program crashed just like in yesterday's article. Except that yesterday we had a FormatException, while this time we have a DivideByZeroException. You'll start to notice a pattern here: errors such as these are called exceptions. When an exception occurs, we're in trouble, and we have to do something about it.

So what we do is wrap the messy code in a try/catch block as follows:

try
{
int x = 5;
int y = 0;
int z = x / y;
Console.WriteLine("The value of z is {0}", z);
}
catch(Exception ex)
{
Console.WriteLine("Uh oh... Chuck Norris just roundhouse-kicked this program.");
}

Console.Write("Press any key to continue . . . ");

Does this look weird? Don't worry - that's because it is. This is called structured exception handling, and not everyone likes it (check out what Joel Spolsky has to say about exceptions).

It's actually more straightforward than it looks. Your program goes into the try block and starts executing each statement one by one, as before. When something explodes (in this case, due to division by zero), the program jumps out of the try block (skipping everything else that's in it - in this case, the code that writes the value of z to the console window) and into the catch block. The catch block defines what the program needs to do when an exception occurs. When you run (F5) this program, here's what you get:

As you can see, only the Console.WriteLine() within the catch block got executed, because the one in the try block got skipped when the DivisionByZeroException was thrown in the previous line. After the catch block, code execution resumes as normal.

Now, try changing the value of y to 2 instead of 0:

int y = 2;

Since we are no longer dividing by zero, Chuck Norris is happy, and the output is different:

However, that isn't quite what we expected, right? I mean, 5 divided by 2 is supposed to give you 2.5, not 2. The problem here is that we are dealing exclusively with integers, so when you divide 5 by 2, the integer part of the result is kept, and the fraction is lost. To do a division that preserves the fraction part, we need to use a different data type, such as float, but more on that another time.

For now, suffice to say that subtraction and divison aren't the only operations you can do with integers. How about addition?

int a = 5 + 3// a is 8

Or maybe a bit of multiplication?

int b = a * 2// b is 16

There's even this thing called modulus, that gives you the remainder of a division operation. For example, 14 divided by 3 gives you 4 remainder 2. The 4 is the result of the division operation (/), while the 2 is the result of a modulus operation (%):

int c = 14 / 3// c is 4
int d = 14 % 3// d is 2

Now let's say you have another variable, and you deduct a value from itself:

int e = 20;
e = e - 1// e is 19

...there is a shorthand for that, which is:

e -= 1// e is 18

In general, when you say x -= y, it's the same as x = x - y. The same holds true for the other arithmetic operations: x *= y is the same as x = x * y, and so on.

Great! This article showed a bit more about what you can do with integers in terms of arithmetic operations, and explained how to deal with circumstances where exceptions are thrown. We can handle the exception at the end of C# Basics: Fun with Integers exactly this way. You can do that as an exercise if you wish. Stick around - more programming tutorials are on their way!