Guy Joel McLean
Guy Joel McLean

Reputation: 1049

Simple "catching" logic

I have a string^ that's being converted to a Uint32 In the code below:

try
{
    int newX = System::Convert::ToUInt32(this->cbXSizeBox->Text);
}
catch (FormatException^ e)
{
    printf("\nNot a valid 3-digit number");
    this->cbXSizeBox->Text = System::Convert::ToString(capBoxSize->x);
}

This works fine.(FYI capBoxSize->x is another value that can evaluate to uint32).

Basically the catch is to snap the value of cbXSizeBox->Text (which is a string), back to it's default value, should the user enter anything but numbers (e.g. 2g9).

In the event that the catch block doesn't catch a format exception, I would like to add code to change the value of capBoxSize->x to it's new valid value. I'm trying to find something that says to the compiler, "if you catch this exception, do this. But If you don't catch the exception, do this." Is it possible to wrap a catch block in an if else statement?

If you understand what I'm trying to do, any suggestions would be appreciated.

P.S. Putting the code to change capBoxSize->x in the try block isn't really an option I think. As this could attempt assigning newX as something like "2ty" to capBoxSize->X, which is a Uint32. Which may cause errors.

Upvotes: 1

Views: 103

Answers (2)

Konrad Rudolph
Konrad Rudolph

Reputation: 546073

No need for an else block, just put the formatting after the actual parsing:

try {
    int newX = System::Convert::ToUInt32(this->cbXSizeBox->Text);
    capBoxSize->x = newX;
}
catch (FormatException^ e) {
    printf("\nNot a valid 3-digit number");
    this->cbXSizeBox->Text = System::Convert::ToString(capBoxSize->x);
}

Actually there’s no need for the temporary newX, just assign it directly:

capBoxSize->x = System::Convert::ToUInt32(this->cbXSizeBox->Text);

Putting the code to change capBoxSize->x in the try block isn't really an option I think. As this could attempt assigning newX as something like "2ty" to capBoxSize->X, which is a Uint32.

That will never happen because at this point your code has already thrown an exception and has consequently left the try block and entered the catch block.


That said, I would avoid try…catch here and use System::Int32::TryParse instead.

Upvotes: 5

scaryrawr
scaryrawr

Reputation: 867

I think something along the lines of:

bool exception_caught = false;
try {
    int newX = System::Convert::ToUInt32(this->cbXSizeBox->Text);
} catch (FormatException ^e) {
    //  Format exception code.
    exception_caught = true;
    // Handle Exception stuff
}

if (!exception_caught) {
    //  Other stuff.
}

Upvotes: 0

Related Questions