Public Group

# Help with understanding parts of this C# program?

This topic is 2114 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

## Recommended Posts

So I have someone teaching me Blitz and C++ and I wanted to find out exactly where I was so I went skimming through my old C# book "Programming in the Key of C# by Charles Petzold" and I found where  I briefly left off. Here is an example code from the chapter that I left off on:

using System;

class MethodWithThrows
{
static void Main()
{
int iInput;
Console.WriteLine("Enter an unsigned Integer; ");
try
{
Console.WriteLine("You entered {0}", iInput);
}
catch (Exception exc)
{
Console.WriteLine(exc.Message);
}
}

static int MyParse(string str)
{
int iResult = 0, i = 0;

if (str == null)
throw new ArgumentNullException();

str = str.Trim();
if (str.Length == 0)
throw new FormatException ();

while ( i < str.Length)
{
if (!Char.IsDigit(str, i))
throw new FormatException();
iResult = checked(10 * iResult + (int) str[i] - (int) '0');
i++;
}
return iResult;
}
}


I'm having problems understanding the following lines:

Line 9: Try. I Don't recall ever learning about try in the book. What does it mean and what does it do?

Line 11: MyParse. I have never heard of this either. Is it a class declaration in the System namespace?

Line 14: catch (Expection exc). I seem to recall reading about catch somewhere but I don't remember what it is and what it does.

Line 16: exc.Message. Again never heard of it and is it a class declaration in the System namespace?

Line 20: We return to MyParse I understand the rest of the line. We're declaring a function here.

Line 25: Throw New ArgumentNullException(). I never recall learning about Throw or New. ArgumentNullException sounds self explanatory and I can guess what this line means. It just means if the integer str is null the program throws a null exception?

Line 27: StrTrim(); Never heard of this function before.

Line 29: We're returning to Throw and New again and what is a format exception?

Line 36: i++ I recall this numerator. But I don't remember exactly what it means.

The rest of it I understand and consider it almost a cakewalk.

##### Share on other sites

If code within a try block throws an exception then the catch block should run if there is a catch with the right type of exception.  throw is an example of a thrown exception.

i++ is the same as i += 1, maybe a bit more optimized though.  Also technically the operator that should of been called is ++i; to many programmers get this wrong even though its clearly the wrong operator, however in both cases the i gets incremented.

##### Share on other sites

Line 9: Try is a keyword that makes the code try to execute the code in the braces below it. If there is an error of some sort, called an exception, it can be caught by another block afterwards instead of crashing the program.

Line 11: MyParse is a function that is declared a bit later in the code. You are just calling that. In C#, unlike C++, you don't have to declare a function before it is used.

Line 14: This is the catch header for the try block. If there is an error that is of the type Exception (which is the superclass of all exceptions) in the try block, it will execute this block instead of crashing. You can use a more specific exception type as well to make it catch that type of error without catching others if you want as well. Probably a good idea to do so infact.

Line 16: exc is the exception instance that caused this error, declared in the catch header. Message is a string that is in it that describes the error. So this is just printing the error to the console and continuing on with the program.

Line 20: Here as you say, you are declaring the function MyParse.

Line 25: throw means take the exception instance that is passed to it and make it an error. This will be caught by the try/catch block in Main. The new is used to make a new instance of the exception type. So this means if str, which is the arguement passed into the function, is null, send up an error about the arguement being null.

Line 27: I am not familiar with the C# libraries, but I would guess that StrTrim gets rid of the whitespace at the beginning and the end of the string. So "  Hello World    " would change to "Hello World".

Line 29: Again this is to send up an error to be caught by a try/catch block or crash the program. In this case the type of the exception is a FormatException instead. FormatExceptions are for if something is formatted incorrectly. In this case, is the string passed into the function is empty after leading and trailing whitespace is stripped, you didn't actually send anything into the function and that is not allowed by the function, hence the FormatException.

Line 36: i++ is similar but not exactly the same as i = i + 1 or ++i or i += 1. In this example, they are all functionally identical. There are some differences in certain circumstances though, mostly regarding when the number is increased. So it just makes the number in i go up one.

##### Share on other sites

Look up "exception handling" for info on the keywords try, catch, and throw. It's one of many ways to handle errors. In this case, it's just verifying that the user typed in a number and nothing else.

MyParse on line 9 is a function call. Inside the function (defined below), if the string is formatted incorrectly, it throws an exception. That bails out of the function, and into the catch block, where an error message is displayed. If the string is good, and no exception is thrown, then the catch block is never executed.

Line 14 is declaring a variable of type Exception, named exc, sort of like a function definition. When an exception gets thrown by something in the preceding try block, if it's compatible with the variable type in the catch block's declaration, then the exception object is passed in and the catch block executed. Otherwise it continues up the call stack looking for a catch block with a compatible variable type. Since Exception is the parent class of both FormatException and ArgumentNullException, it's compatible.

Exception, FormatException, and ArgumentNullException are in System, which the using System; up top makes available without having to type System.Exception.

Line 16: Message is property of the System.Exception class, automatically filled out in the constructors of FormatException and ArgumentNullException.

Line 25: As said, throw bails out of the function and looks for the first catch block that takes a compatible exception type. The new keyword means to create an object of the following class type.

Line 27: Trim removes any whitespace characters (spaces, tabs, newlines) from the beginning and end of the string.

Line 36: ++ is the increment operator. i++ is the same as i = i + 1

##### Share on other sites
try/catch/throw/finally are keywords used for "exception handling" in C#. Exception handling is one kind of error handling.

When code encounters a situation that it doesn't know how to handle (or doesn't WANT to handle), it can choose to abort what it's currently doing by "throwing" an exception. An exception is an object (in most cases just containing a message about what went wrong and the call stack where the problem occurred).

When an exception is thrown, the program stops executing your code and does this instead:

1. Find the most recently entered "try" block. If one isn't found, the program usually crashes with an "unhandled exception" message.
2. Assuming a try block was found, it may have zero or more catch blocks and/or one finally block immediately after it. At least one catch/finally block must exist per try block.
3a. If any catch blocks exist, find the first one where the exception's type can be stored in the variable defined by the catch.
3b. If a catch block passes this test, the program resumes executing your code at that point and ignores the remaining catch blocks.
3c. If there is a finally block, it is always executed at this point unless the program is forcibly exited. It is ALSO executed immediately after the 'try' block even when no exceptions occur.
3d. If no catch blocks caught the exception, the program finds the previous 'try' block and starts over at the first step. Edited by Nypyren

##### Share on other sites

So I have someone teaching me Blitz and C++ and I wanted to find out exactly where I was so I went skimming through my old C# book "Programming in the Key of C# by Charles Petzold"

I have no idea how those 3 languages fit in with each other. However, wouldn't it be best to ask the person teaching you what those are?

##### Share on other sites

I think you should consider starting again, or going back further in the book, as you clearly have forgotten some of the fundamentals. Remember, programming is a practical skill, you must write lots of programs before some of the more advanced concepts will stick. The book should include some exercises at the end of each chapter, you should try to complete as many of these as you can - you can post your attempt here if you get stuck on a particular exercise.

Edited by rip-off

##### Share on other sites

I think you should consider starting again, or going back further in the book, as you clearly have forgotten some of the fundamentals. Remember, programming is a practical skill, you must write lots of programs before some of the more advanced concepts will stick. The book should include some exercises at the end of each chapter, you should try to complete as many of these as you can - you can post your attempt here if you get stuck on a particular exercise.

"That's a Fact, Jack" - Many books teaching you a language present you with the basic concepts of what they are trying to show you.  It is up to you to apply those concepts in as many different ways as possible so that you can understand how they work alone and  how they will work with other concepts that are being presented earlier.  You have to figure out how to tie them all together.  This what a tudour should be able to do "GrassHopper", Present you with concepts and then tie them together.

If you do not understand what is being presented in the book, back up and re-enforce the parts you do understand and look at how the new concepts tie in with the old.

Be patient,  If your tudour is any good, he or she will tie them together.  No matter what language you are being taught in, The coding commands might be a little different, but the concepts should be the same.

Edited by Poigahn

##### Share on other sites

As you learn programming, one of the most important skills will also be learning what to enter into google to get the answers you want.  Normally start with this pattern if you don't know any better - "language class method" and "language keyword", ie "C# sting Trim" - you will see this is the first result, and is the documentation for that method - http://msdn.microsoft.com/en-us/library/t97s7bs3.aspx or "C# try" - from which most of the results would help teach you the concept of try/catch (aka exception handling).

Notice that for this to be possible you have to be able to identify what TYPE a variable you are looking at is.  Often, if you can't tell just by reading, if you are in Visual Studio you can just hover your mouse over the variable name and it will show you the type.  Or you can right-click on the variable name and select "go to definition" and see the declaration of the variable, which should normally include the type (except when they use the "var" keyword).  You can also use this trick on methods.  If you use "go to definition" on MyParse it takes you to the first line in the file creating that method, whereas if you do the same thing on "Trim()" it opens a window representing all the public methods of the String class, and you can see that that method is declared in the string class (and then google away).

Also, once you know more about what you want (ie the name of a concept), then use that in your search query too, and sometimes add terms such as "tutorial" or "reference" to filter down to the type of post you are looking for, such as "C# exception handling tutorial".

good luck.

• 21
• 11
• 9
• 17
• 13