1

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.

4

2 回答 2

5

不需要else块,只需在实际解析后放置格式即可:

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);
}

其实不需要临时的newX,直接赋值即可:

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

我认为将代码更改 capBoxSize->x 放在 try 块中并不是一个真正的选择。因为这可能会尝试将 newX 作为“2ty”分配给 capBoxSize->X,它是一个 Uint32。

这永远不会发生,因为此时您的代码已经抛出异常,因此离开了try块并进入了catch块。


也就是说,我会避免try…catch在这里使用System::Int32::TryParse

于 2013-06-22T14:21:12.720 回答
0

我认为是这样的:

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.
}
于 2013-06-22T14:17:09.927 回答