Добавил:
Опубликованный материал нарушает ваши авторские права? Сообщите нам.
Вуз: Предмет: Файл:
CSharpNotesForProfessionals.pdf
Скачиваний:
65
Добавлен:
20.05.2023
Размер:
6.12 Mб
Скачать

Chapter 78: Handling FormatException when converting string to other types

Section 78.1: Converting string to integer

There are various methods available for explicitly converting a string to an integer, such as:

1.Convert.ToInt16();

2.Convert.ToInt32();

3.Convert.ToInt64();

4.int.Parse();

But all these methods will throw a FormatException, if the input string contains non-numeric characters. For this, we need to write an additional exception handling(try..catch) to deal them in such cases.

Explanation with Examples:

So, let our input be:

string inputString = "10.2";

Example 1: Convert.ToInt32()

int convertedInt = Convert.ToInt32(inputString); // Failed to Convert // Throws an Exception "Input string was not in a correct format."

Note: Same goes for the other mentioned methods namely - Convert.ToInt16(); and Convert.ToInt64();

Example 2: int.Parse()

int convertedInt = int.Parse(inputString); // Same result "Input string was not in a correct format.

How do we circumvent this?

As told earlier, for handling the exceptions we usually need a try..catch as shown below:

try

{

string inputString = "10.2";

int convertedInt = int.Parse(inputString);

}

catch (Exception Ex)

{

//Display some message, that the conversion has failed.

}

But, using the try..catch everywhere will not be a good practice, and there may be some scenarios where we wanted to give 0 if the input is wrong, (If we follow the above method we need to assign 0 to convertedInt from the catch block). To handle such scenarios we can make use of a special method called .TryParse().

GoalKicker.com – C# Notes for Professionals

464

The .TryParse() method having an internal Exception handling, which will give you the output to the out parameter, and returns a Boolean value indicating the conversion status (true if the conversion was successful; false if it failed). Based on the return value we can determine the conversion status. Lets see one Example:

Usage 1: Store the return value in a Boolean variable

int convertedInt; // Be the required integer

bool isSuccessConversion = int.TryParse(inputString, out convertedInt);

We can check The variable isSuccessConversion after the Execution to check the conversion status. If it is false then the value of convertedInt will be 0(no need to check the return value if you want 0 for conversion failure).

Usage 2: Check the return value with if

if (int.TryParse(inputString, out convertedInt))

{

//convertedInt will have the converted value

//Proceed with that

}

else

{

// Display an error message

}

Usage 3: Without checking the return value you can use the following, if you don't care about the return value

(converted or not, 0 will be ok)

int.TryParse(inputString, out convertedInt);

//use the value of convertedInt

//But it will be 0 if not converted

GoalKicker.com – C# Notes for Professionals

465

Chapter 79: Read & Understand

Stacktraces

A stack trace is a great aid when debugging a program. You will get a stack trace when your program throws an Exception, and sometimes when the program terminates abnormally.

Section 79.1: Stack trace for a simple NullReferenceException in Windows Forms

Let's create a small piece of code that throws an exception:

private void button1_Click(object sender, EventArgs e)

{

string msg = null; msg.ToCharArray();

}

If we execute this, we get the following Exception and stack trace:

System.NullReferenceException: "Object reference not set to an instance of an object." at WindowsFormsApplication1.Form1.button1_Click(Object sender, EventArgs e) in

F:\WindowsFormsApplication1\WindowsFormsApplication1\Form1.cs:line 29 at System.Windows.Forms.Control.OnClick(EventArgs e)

at System.Windows.Forms.Button.OnClick(EventArgs e)

at System.Windows.Forms.Button.OnMouseUp(MouseEventArgs mevent)

The stack trace goes on like that, but this part will su ce for our purposes.

At the top of the stack trace we see the line:

at WindowsFormsApplication1.Form1.button1_Click(Object sender, EventArgs e) in F:\WindowsFormsApplication1\WindowsFormsApplication1\Form1.cs:line 29

This is the most important part. It tells us the exact line where the Exception occurred: line 29 in Form1.cs . So, this is where you begin your search.

The second line is

at System.Windows.Forms.Control.OnClick(EventArgs e)

This is the method that called button1_Click. So now we know that button1_Click, where the error occurred, was called from System.Windows.Forms.Control.OnClick.

We can continue like this; the third line is

at System.Windows.Forms.Button.OnClick(EventArgs e)

This is, in turn, the code that called System.windows.Forms.Control.OnClick.

The stack trace is the list of functions that was called until your code encountered the Exception. And by following

GoalKicker.com – C# Notes for Professionals

466

this, you can figure out which execution path your code followed until it ran into trouble!

Note that the stack trace includes calls from the .Net system; you don't normally need to follow all Microsofts System.Windows.Forms code to find out what went wrong, only the code that belongs to your own application.

So, why is this called a "stack trace"?

Because, every time a program calls a method, it keeps track of where it was. It has a data structure called the "stack", where it dumps its last location.

If it is done executing the method, it looks on the stack to see where it was before it called the method - and continues from there.

So the stack lets the computer know where it left o , before calling a new method.

But it also serves as a debugging help. Like a detective tracing the steps that a criminal took when committing their crime, a programmer can use the stack to trace the steps a program took before it crashed.

GoalKicker.com – C# Notes for Professionals

467