Try Catch End Try nor (really) working!

To all



In a lot of example the following lines of codes exist to try to check the type of part being used before executing the main code. I am testing it be making sure that I am not in a .fem but the code produces an lengthy error message (clearly linked to the fact that I am not executing it from a .fem) but not the expected message box. Does anyone have any idea/suggestion as to why is that?



Thanks



Regards



JXB


'----------------------------------------

Dim basePart As BasePart = theSession.Parts.BaseWork

Dim femPart As CAE.FemPart
Try
femPart = CType(basePart, CAE.FemPart)
Catch ex As NXException
Dim Msg as String = "Macro only works on a FEM part"
'Style = vbOKOnly + vbCritical
Dim Title as String = "Macro's Name"
MsgBox(Msg, vbOKOnly + vbCritical, Title)
Exit Sub
End Try

The problem is, we are trying to catch the wrong type of error (I made the same mistake in the "report mesh" code I gave you a short time ago).



The CType command is a .net command that allows you to cast from one object type to another (if they are compatible). If it throws an error, it will be of type "Exception", not "NXException" as the error will be thrown by the .net API, not the NXOpen API. To fix it, change the line:


Catch ex As NXException

to this:

Catch ex As Exception

Thanks. Spot on !

Thanks
Regards

For these sorts of situations, I recommend the VB TryCast function, instead. The idea is that you cast your basePart to type CAE.FemPart, as in the code above, but you use TryCast instead of CTYpe. If basePart is actually of type CAE.FemPart, the cast will work, and you're done. If not, the result will be Nothing. No Exceptions are involved, so you don't have to mess around with Try/Catch stuff.


Dim basePart As BasePart = theSession.Parts.BaseWork
Dim femPart As CAE.FemPart = TryCast(basePart, CAE.FemPart)
If femPart Is Nothing
'Issue error message
' Exit
End If
' We have a CAE.FemPart -- proceed

Thanks Ciao for the advice. Much appreciated

Thanks
Regards