Throws an exception when a cast is unsuccessful.
__try_cast < type-id > ( expression )
The __try_cast keyword provides support for automatically throwing an exception (of type System::InvalidCastException) whenever the specified casting operation fails.
The __try_cast keyword can be used during the testing phase of your application, automatically alerting you to possible casting failures. After your application has completed testing, you can replace the __try_cast keyword with static_cast.
#using <mscorlib.dll> #using namespace System; __gc struct Base { }; __gc struct Derived : Base { }; __gc struct MoreDerived : Derived { }; void main() { Base*bp = new Derived; try { MoreDerived* mdp = __try_cast<MoreDerived*>(bp); } catch(System::InvalidCastException*) { Console::WriteLine("Could not cast 'bp' to MoreDerived*"); }
Managed Extensions for C++ Keywords | __gc | dynamic_cast | Handling Exceptions Using Managed Extensions for C++ | C++ Keywords