I am wondering can try..catch
force execution to go into the catch
and run code in there?
here example code:
try {
if (
Slight resurrection, but I wanted to add both a sample (primarily like others) and a use case.
public int GetValueNum(string name)
{
int _ret = 0;
try
{
Control c = (extendedControls.Single(s => s.ValueName == name) as Control);
if (c.GetType() == typeof(ExtendedNumericUpDown))
_ret = (int)((ExtendedNumericUpDown)c).Value;
else
throw new Exception();
}
catch
{
throw new InvalidCastException(String.Format("Invalid cast fetching .Value value for {0}.\nExtendedControllerListener.GetValueNum()", name));
}
return _ret;
}
In my case, I have custom controls - a handful of controls that use a base Windows.Forms control, but add two bools and a string for tracking, and also automatically get registered to a Singleton List
so they can be properly fetched without drilling down through control containers (it's a tabbed form).
In this case, I'm creating some methods to easily get values (.Value, .Text, .Checked, .Enabled
) by a name string. In the case of .Value
, not all Control
objects have it. If the extended control is not of type ExtendedNumericUpDown
, it IS an InvalidCastException
as the method should not be called against that type of control. This isn't flow, but the prescribed usage of invalid cast. Since Control
doesn't naturally have a .Value
property, Visual Studio won't let me just force an attempt and fail after.