Exception Handling - Part One

本文讨论了何时创建自定义异常类以及如何在Java中进行异常处理。包括使用平台提供的异常类、创建自定义异常类的条件、异常类型的选择、避免捕获所有可能的异常、明确异常的影响以及根据不同情况采取的错误处理策略。

1. Do i need to create a new exception class ?

    When faced with choosing the type of exception to throw, you can either use one written by someone else — the Java platform provides a lot of exception classes you can use — or you can write one of your own. You should write your own exception classes if you answer yes to any of the following questions; otherwise, you can probably use someone else's.

    Do you need an exception type that isn't represented by those in the Java platform?
    Would it help users if they could differentiate your exceptions from those thrown by classes written by other vendors?
    Does your code throw more than one related exception?
    If you use someone else's exceptions, will users have access to those exceptions? A similar question is, should your package be independent and self-contained?
    
2.
Normally don't throw some exceptions which you don't have control(not part of your code), instead, you can create your own exceptions and catch the relevant exceptions fronm downstream
and throw your own exceptions, e.g. you can catch various exceptions from downstream when you send emails, but you just throw one "EmailException" in your program,
so the caller in your program will simply handle the "EmailException", and it can easily identify that this exception is thrown by the program code(can judge from the namespace or package name).

3.
In java, RuntinmeException is the unchecked exception, so it's not necessarily part of the method signiture, as there be various types of runtime exceptions thrown, normally you don't know how to handle all of them.

4.
When writting some method, if something is not expected, e.g. the input data is not right or not supported, you need to raise an exception to the caller, so that it knows what happened instead of getting some null or empty result.

e.g. in the following factory method:

    public static Car createCar(CarMaker carMaker, CarType carType) throws CarException {
        Car resultCar;

        if(carType == CarType.BMWCar){
            try{
                resultCar = carMaker.createCar();
                resultCar.init();
            } catch(CarMakingException carMakingException){
                throw new CarException("Failed to create a BMW Car", carMakingException);
            }
        } else {
            throw new RuntimeException("Car type not supported");
        }

        return resultCar;
    }

    a. We need to assert other types of cars, i.e. for not supported car types, we also need to handle properly instead of return a null object to the caller.
    b. If input data not valid, e.g. the car type is not supported here, then we will raise an error to the caller, so that it knows what happened essentially.
    
5.
Dont' try to catch all the possible exceptions.

In some case, you don't know how to handle the exceptions, for these exceptions, you don't know the implication,
then just leave it, it's fine that program crach or shut down suddenly due to these exceptions. We should not try to catch and handle in such case, it might be leaving the application keeping doig the wrong things and nobody will knows as it seems the exception is already handled "nicely".

6. Know clearly what are the implication of the exception

In case of exception, you can either exit the app or just write some error log or simply raise an warning alert to user in the GUI.

This really depends on the implication:
If the exception is fatal, e.g. the data might be massed up, then you have to exit the app and shut down it immediately.
If the exception is some merely a user error, then you can raise an alert in the GUI.
If the exception is not critical and it's a backgroud process, then program can simply wirte a exception log entry for that.

In other cases, it is the caller to depends how to handle the error appropriately.


//============================================================================== // WARNING!! This file is overwritten by the Block UI Styler while generating // the automation code. Any modifications to this file will be lost after // generating the code again. // // Filename: D:\001 NX Model\000 NX Custom Development\ART_NX_C\ArkTech\Modeling_Custom.cs // // This file was generated by the NX Block UI Styler // Created by: jzk24 // Version: NX 2406 // Date: 08-30-2025 (Format: mm-dd-yyyy) // Time: 12:07 (Format: hh-mm) // //============================================================================== //============================================================================== // Purpose: This TEMPLATE file contains C# source to guide you in the // construction of your Block application dialog. The generation of your // dialog file (.dlx extension) is the first step towards dialog construction // within NX. You must now create a NX Open application that // utilizes this file (.dlx). // // The information in this file provides you with the following: // // 1. Help on how to load and display your Block UI Styler dialog in NX // using APIs provided in NXOpen.BlockStyler namespace // 2. The empty callback methods (stubs) associated with your dialog items // have also been placed in this file. These empty methods have been // created simply to start you along with your coding requirements. // The method name, argument list and possible return values have already // been provided for you. //============================================================================== //------------------------------------------------------------------------------ //These imports are needed for the following template code //------------------------------------------------------------------------------ using NXOpen; using NXOpen.BlockStyler; using NXOpen.UF; using NXOpen.Utilities; using System; using static NXOpen.BodyDes.OnestepUnformBuilder; using OnestepPart = NXOpen.BodyDes.OnestepUnformBuilder.Part; // 为另一个 Part 定义别名 using Part = NXOpen.Part; //------------------------------------------------------------------------------ //Represents Block Styler application class //------------------------------------------------------------------------------ public class Modeling_Custom { //class members private static Session theSession = null; private static UI theUI = null; private string theDlxFileName; private NXOpen.BlockStyler.BlockDialog theDialog; private NXOpen.BlockStyler.Group group1;// Block type: Group private NXOpen.BlockStyler.Enumeration enum0;// Block type: Enumeration private NXOpen.BlockStyler.StringBlock string0;// Block type: String private NXOpen.BlockStyler.StringBlock string01;// Block type: String private NXOpen.BlockStyler.Group group;// Block type: Group private NXOpen.BlockStyler.StringBlock string02;// Block type: String private Part workPart; //------------------------------------------------------------------------------ //Constructor for NX Styler class //------------------------------------------------------------------------------ public Modeling_Custom() { try { theSession = Session.GetSession(); theUI = UI.GetUI(); theDlxFileName = "Modeling_Custom.dlx"; theDialog = theUI.CreateDialog(theDlxFileName); theDialog.AddApplyHandler(new NXOpen.BlockStyler.BlockDialog.Apply(apply_cb)); theDialog.AddOkHandler(new NXOpen.BlockStyler.BlockDialog.Ok(ok_cb)); theDialog.AddUpdateHandler(new NXOpen.BlockStyler.BlockDialog.Update(update_cb)); theDialog.AddInitializeHandler(new NXOpen.BlockStyler.BlockDialog.Initialize(initialize_cb)); theDialog.AddDialogShownHandler(new NXOpen.BlockStyler.BlockDialog.DialogShown(dialogShown_cb)); } catch (Exception ex) { //---- Enter your exception handling code here ----- throw ex; } } //------------------------------- DIALOG LAUNCHING --------------------------------- // // Before invoking this application one needs to open any part/empty part in NX // because of the behavior of the blocks. // // Make sure the dlx file is in one of the following locations: // 1.) From where NX session is launched // 2.) $UGII_USER_DIR/application // 3.) For released applications, using UGII_CUSTOM_DIRECTORY_FILE is highly // recommended. This variable is set to a full directory path to a file // containing a list of root directories for all custom applications. // e.g., UGII_CUSTOM_DIRECTORY_FILE=$UGII_BASE_DIR\ugii\menus\custom_dirs.dat // // You can create the dialog using one of the following way: // // 1. Journal Replay // // 1) Replay this file through Tool->Journal->Play Menu. // // 2. USER EXIT // // 1) Create the Shared Library -- Refer "Block UI Styler programmer's guide" // 2) Invoke the Shared Library through File->Execute->NX Open menu. // //------------------------------------------------------------------------------ public static void Main() { Modeling_Custom theModeling_Custom = null; try { theModeling_Custom = new Modeling_Custom(); // The following method shows the dialog immediately theModeling_Custom.Launch(); } catch (Exception ex) { //---- Enter your exception handling code here ----- theUI.NXMessageBox.Show("Block Styler", NXMessageBox.DialogType.Error, ex.ToString()); } finally { if (theModeling_Custom != null) theModeling_Custom.Dispose(); theModeling_Custom = null; } } //------------------------------------------------------------------------------ // This method specifies how a shared image is unloaded from memory // within NX. This method gives you the capability to unload an // internal NX Open application or user exit from NX. Specify any // one of the three constants as a return Value to determine the type // of unload to perform: // // // Immediately : unload the library as soon as the automation program has completed // Explicitly : unload the library from the "Unload Shared Image" dialog // AtTermination : unload the library when the NX session terminates // // // NOTE: A program which associates NX Open applications with the menubar // MUST NOT use this option since it will UNLOAD your NX Open application image // from the menubar. //------------------------------------------------------------------------------ public static int GetUnloadOption(string arg) { //return System.Convert.ToInt32(Session.LibraryUnloadOption.Explicitly); return System.Convert.ToInt32(Session.LibraryUnloadOption.Immediately); // return System.Convert.ToInt32(Session.LibraryUnloadOption.AtTermination); } //------------------------------------------------------------------------------ // Following method cleanup any housekeeping chores that may be needed. // This method is automatically called by NX. //------------------------------------------------------------------------------ public static void UnloadLibrary(string arg) { try { //---- Enter your code here ----- } catch (Exception ex) { //---- Enter your exception handling code here ----- theUI.NXMessageBox.Show("Block Styler", NXMessageBox.DialogType.Error, ex.ToString()); } } //------------------------------------------------------------------------------ //This method launches the dialog to screen //------------------------------------------------------------------------------ public NXOpen.BlockStyler.BlockDialog.DialogResponse Launch() { NXOpen.BlockStyler.BlockDialog.DialogResponse dialogResponse = NXOpen.BlockStyler.BlockDialog.DialogResponse.Invalid; try { dialogResponse = theDialog.Launch(); } catch (Exception ex) { //---- Enter your exception handling code here ----- theUI.NXMessageBox.Show("Block Styler", NXMessageBox.DialogType.Error, ex.ToString()); } return dialogResponse; } //------------------------------------------------------------------------------ //Method Name: Dispose //------------------------------------------------------------------------------ public void Dispose() { if (theDialog != null) { theDialog.Dispose(); theDialog = null; } } //------------------------------------------------------------------------------ //---------------------Block UI Styler Callback Functions-------------------------- //------------------------------------------------------------------------------ //------------------------------------------------------------------------------ //Callback Name: initialize_cb //------------------------------------------------------------------------------ public void initialize_cb() { try { group1 = (NXOpen.BlockStyler.Group)theDialog.TopBlock.FindBlock("group1"); enum0 = (NXOpen.BlockStyler.Enumeration)theDialog.TopBlock.FindBlock("enum0"); string0 = (NXOpen.BlockStyler.StringBlock)theDialog.TopBlock.FindBlock("string0"); string01 = (NXOpen.BlockStyler.StringBlock)theDialog.TopBlock.FindBlock("string01"); group = (NXOpen.BlockStyler.Group)theDialog.TopBlock.FindBlock("group"); string02 = (NXOpen.BlockStyler.StringBlock)theDialog.TopBlock.FindBlock("string02"); //------------------------------------------------------------------------------ //Registration of StringBlock specific callbacks //------------------------------------------------------------------------------ //string0.SetKeystrokeCallback(new NXOpen.BlockStyler.StringBlock.KeystrokeCallback(KeystrokeCallback)); //string01.SetKeystrokeCallback(new NXOpen.BlockStyler.StringBlock.KeystrokeCallback(KeystrokeCallback)); //string02.SetKeystrokeCallback(new NXOpen.BlockStyler.StringBlock.KeystrokeCallback(KeystrokeCallback)); //------------------------------------------------------------------------------ } catch (Exception ex) { //---- Enter your exception handling code here ----- theUI.NXMessageBox.Show("Block Styler", NXMessageBox.DialogType.Error, ex.ToString()); } } //------------------------------------------------------------------------------ //Callback Name: dialogShown_cb //This callback is executed just before the dialog launch. Thus any Value set //here will take precedence and dialog will be launched showing that Value. //------------------------------------------------------------------------------ public void dialogShown_cb() { try { //---- Enter your callback code here ----- } catch (Exception ex) { //---- Enter your exception handling code here ----- theUI.NXMessageBox.Show("Block Styler", NXMessageBox.DialogType.Error, ex.ToString()); } } //------------------------------------------------------------------------------ //Callback Name: apply_cb //------------------------------------------------------------------------------ public int apply_cb() { int errorCode = 0; try { workPart = theSession.Parts.Work; if (workPart == null) { theUI.NXMessageBox.Show("错误", NXMessageBox.DialogType.Error, "没有打开的零件文件"); return errorCode; } // 1. 将enum0的值赋予"型号"属性 string modelType = enum0.ValueAsString; SetPartProperty(workPart, "型号", modelType); // 2. 将string0的值赋予"DB_PART_NO"属性 string partNo = string0.Value; if (!string.IsNullOrEmpty(partNo)) { SetPartProperty(workPart, "DB_PART_NO", partNo); } else { theUI.NXMessageBox.Show("警告", NXMessageBox.DialogType.Warning, "零件编号不能为空"); } // 3. 将string01的值赋予"DB_PART_NAME"属性 string partName = string01.Value; SetPartProperty(workPart, "DB_PART_NAME", partName); // 4. 将string02的值设置为与string0相同 string02.Value = string0.Value; theUI.NXMessageBox.Show("成功", NXMessageBox.DialogType.Information, "属性已成功更新"); } catch (Exception ex) { //---- Enter your exception handling code here ----- errorCode = 1; theUI.NXMessageBox.Show("Block Styler", NXMessageBox.DialogType.Error, ex.ToString()); } return errorCode; } private void SetPartProperty(Part workPart, string propertyName, string propertyValue) { try { // 检查部件是否为空 if (workPart == null) { theUI.NXMessageBox.Show("错误", NXMessageBox.DialogType.Error, "部件为空"); return; } // 使用 UFUN 检查部件是否可写 if (!IsPartWriteable(workPart)) { theUI.NXMessageBox.Show("错误", NXMessageBox.DialogType.Error, "部件不可写"); return; } // 使用 UFUN 设置属性 UFSession ufSession = UFSession.GetUFSession(); int result= ufSession.Attr.SetStringUserAttribute( workPart.Tag, propertyName, 0, propertyValue, UFAttr.Equals); if (result !=0) { // 处理错误 theUI.NXMessageBox.Show("属性设置警告", NXMessageBox.DialogType.Warning, $"属性操作返回代码: {result}"); } } catch (Exception ex) { // 异常处理 theUI.NXMessageBox.Show("设置属性错误", NXMessageBox.DialogType.Error, $"无法设置属性 '{propertyName}':{ex.Message}"); // 注意:这里不应该抛出 NotImplementedException } } // 添加检查部件可写状态的方法 private bool IsPartWriteable(Part part) { try { UFSession ufSession = UFSession.GetUFSession(); int writeStatus; object value = ufSession.Part.AskWriteStatus(part.Tag, out IsPartWriteable); // writeStatus 值为 0 表示部件可写 return IsPartWriteable; } catch { return false; } } //------------------------------------------------------------------------------ //Callback Name: update_cb //------------------------------------------------------------------------------ public int update_cb(NXOpen.BlockStyler.UIBlock block) { try { if (block == enum0) { string02.Value = string0.Value; } else if (block == string0) { //---------Enter your code here----------- } else if (block == string01) { //---------Enter your code here----------- } else if (block == string02) { //---------Enter your code here----------- } } catch (Exception ex) { //---- Enter your exception handling code here ----- theUI.NXMessageBox.Show("Block Styler", NXMessageBox.DialogType.Error, ex.ToString()); } return 0; } //------------------------------------------------------------------------------ //Callback Name: ok_cb //------------------------------------------------------------------------------ public int ok_cb() { int errorCode = 0; try { errorCode = apply_cb(); if (errorCode == 0) { theDialog.Dispose(); } } catch (Exception ex) { //---- Enter your exception handling code here ----- errorCode = 1; theUI.NXMessageBox.Show("Block Styler", NXMessageBox.DialogType.Error, ex.ToString()); } return errorCode; } //------------------------------------------------------------------------------ //StringBlock specific callbacks //------------------------------------------------------------------------------ //public int KeystrokeCallback(NXOpen.BlockStyler.StringBlock string_block, string uncommitted_value) //{ //} //------------------------------------------------------------------------------ //------------------------------------------------------------------------------ //Function Name: GetBlockProperties //Returns the propertylist of the specified BlockID //------------------------------------------------------------------------------ public PropertyList GetBlockProperties(string blockID) { PropertyList plist = null; try { plist = theDialog.GetBlockProperties(blockID); } catch (Exception ex) { //---- Enter your exception handling code here ----- theUI.NXMessageBox.Show("Block Styler", NXMessageBox.DialogType.Error, ex.ToString()); } return plist; } } 发现以下错误:CS1503参数5:无法从"方法组"转换为"bool" CS1061"UFPart"未包含"AskWriteStatus"的定义,并且找不到可接受第一个"UFPart"类型参数的可访问扩展方法"AskWriteStatus"(是否缺少using指令或程序集引用?) CS1657"IsPartWriteable"是一个"方法组",无法用作 ref或cput值 CS0428无法将方法组"IsPartWriteable"转换为非委托类型"bcol"。是否希望调用此方法? CS0168 声明了变量"writeStatus",但从未使用过 CS0168 声明了变量"ex",但从未使用过 CS0168 声明了变量"ex",但从未使用过 CS0168 声明了变量"ex",但从未使用过,请更改
09-02
//============================================================================== // WARNING!! This file is overwritten by the Block UI Styler while generating // the automation code. Any modifications to this file will be lost after // generating the code again. // // Filename: D:\Tool\Application\dzbk.cpp // // This file was generated by the NX Block UI Styler // Created by: liugang0213 // Version: NX 8.5 // Date: 06-13-2025 (Format: mm-dd-yyyy) // Time: 09:46 (Format: hh-mm) // //============================================================================== //============================================================================== // Purpose: This TEMPLATE file contains C++ source to guide you in the // construction of your Block application dialog. The generation of your // dialog file (.dlx extension) is the first step towards dialog construction // within NX. You must now create a NX Open application that // utilizes this file (.dlx). // // The information in this file provides you with the following: // // 1. Help on how to load and display your Block UI Styler dialog in NX // using APIs provided in NXOpen.BlockStyler namespace // 2. The empty callback methods (stubs) associated with your dialog items // have also been placed in this file. These empty methods have been // created simply to start you along with your coding requirements. // The method name, argument list and possible return values have already // been provided for you. //============================================================================== //------------------------------------------------------------------------------ //These includes are needed for the following template code //------------------------------------------------------------------------------ #include "dzbk.hpp" using namespace NXOpen; using namespace NXOpen::BlockStyler; //------------------------------------------------------------------------------ // Initialize static variables //------------------------------------------------------------------------------ Session *(dzbk::theSession) = NULL; UI *(dzbk::theUI) = NULL; //------------------------------------------------------------------------------ // Constructor for NX Styler class //------------------------------------------------------------------------------ dzbk::dzbk() { try { // Initialize the NX Open C++ API environment dzbk::theSession = NXOpen::Session::GetSession(); dzbk::theUI = UI::GetUI(); theDlxFileName = "dzbk.dlx"; theDialog = dzbk::theUI->CreateDialog(theDlxFileName); // Registration of callback functions theDialog->AddApplyHandler(make_callback(this, &dzbk::apply_cb)); theDialog->AddOkHandler(make_callback(this, &dzbk::ok_cb)); theDialog->AddUpdateHandler(make_callback(this, &dzbk::update_cb)); theDialog->AddInitializeHandler(make_callback(this, &dzbk::initialize_cb)); theDialog->AddDialogShownHandler(make_callback(this, &dzbk::dialogShown_cb)); } catch(exception& ex) { //---- Enter your exception handling code here ----- throw; } } //------------------------------------------------------------------------------ // Destructor for NX Styler class //------------------------------------------------------------------------------ dzbk::~dzbk() { if (theDialog != NULL) { delete theDialog; theDialog = NULL; } } //------------------------------- DIALOG LAUNCHING --------------------------------- // // Before invoking this application one needs to open any part/empty part in NX // because of the behavior of the blocks. // // Make sure the dlx file is in one of the following locations: // 1.) From where NX session is launched // 2.) $UGII_USER_DIR/application // 3.) For released applications, using UGII_CUSTOM_DIRECTORY_FILE is highly // recommended. This variable is set to a full directory path to a file // containing a list of root directories for all custom applications. // e.g., UGII_CUSTOM_DIRECTORY_FILE=$UGII_ROOT_DIR\menus\custom_dirs.dat // // You can create the dialog using one of the following way: // // 1. USER EXIT // // 1) Create the Shared Library -- Refer "Block UI Styler programmer's guide" // 2) Invoke the Shared Library through File->Execute->NX Open menu. // //------------------------------------------------------------------------------ extern "C" DllExport void ufusr(char *param, int *retcod, int param_len) { UF_initialize(); dzbk *thedzbk = NULL; try { thedzbk = new dzbk(); // The following method shows the dialog immediately thedzbk->Show(); } catch(exception& ex) { //---- Enter your exception handling code here ----- dzbk::theUI->NXMessageBox()->Show("Block Styler", NXOpen::NXMessageBox::DialogTypeError, ex.what()); } if(thedzbk != NULL) { delete thedzbk; thedzbk = NULL; } } //------------------------------------------------------------------------------ // This method specifies how a shared image is unloaded from memory // within NX. This method gives you the capability to unload an // internal NX Open application or user exit from NX. Specify any // one of the three constants as a return value to determine the type // of unload to perform: // // // Immediately : unload the library as soon as the automation program has completed // Explicitly : unload the library from the "Unload Shared Image" dialog // AtTermination : unload the library when the NX session terminates // // // NOTE: A program which associates NX Open applications with the menubar // MUST NOT use this option since it will UNLOAD your NX Open application image // from the menubar. //------------------------------------------------------------------------------ extern "C" DllExport int ufusr_ask_unload() { //return (int)Session::LibraryUnloadOptionExplicitly; return (int)Session::LibraryUnloadOptionImmediately; //return (int)Session::LibraryUnloadOptionAtTermination; } //------------------------------------------------------------------------------ // Following method cleanup any housekeeping chores that may be needed. // This method is automatically called by NX. //------------------------------------------------------------------------------ extern "C" DllExport void ufusr_cleanup(void) { try { //---- Enter your callback code here ----- } catch(exception& ex) { //---- Enter your exception handling code here ----- dzbk::theUI->NXMessageBox()->Show("Block Styler", NXOpen::NXMessageBox::DialogTypeError, ex.what()); } } int dzbk::Show() { try { theDialog->Show(); } catch(exception& ex) { //---- Enter your exception handling code here ----- dzbk::theUI->NXMessageBox()->Show("Block Styler", NXOpen::NXMessageBox::DialogTypeError, ex.what()); } return 0; } //------------------------------------------------------------------------------ //---------------------Block UI Styler Callback Functions-------------------------- //------------------------------------------------------------------------------ //------------------------------------------------------------------------------ //Callback Name: initialize_cb //------------------------------------------------------------------------------ void dzbk::initialize_cb() { try { qiucha = dynamic_cast<NXOpen::BlockStyler::Group*>(theDialog->TopBlock()->FindBlock("qiucha")); mubiao = dynamic_cast<NXOpen::BlockStyler::BodyCollector*>(theDialog->TopBlock()->FindBlock("mubiao")); group = dynamic_cast<NXOpen::BlockStyler::Group*>(theDialog->TopBlock()->FindBlock("group")); gongju = dynamic_cast<NXOpen::BlockStyler::BodyCollector*>(theDialog->TopBlock()->FindBlock("gongju")); separator0 = dynamic_cast<NXOpen::BlockStyler::Separator*>(theDialog->TopBlock()->FindBlock("separator0")); separator01 = dynamic_cast<NXOpen::BlockStyler::Separator*>(theDialog->TopBlock()->FindBlock("separator01")); juli = dynamic_cast<NXOpen::BlockStyler::DoubleBlock*>(theDialog->TopBlock()->FindBlock("juli")); vector<NXOpen::TaggedObject *> mbt = mubiao->GetSelectedObjects(); for(int a = 0; a < mbt.size(); a++) { tag_t mbttag = mbt[a]->Tag(); UF_DISP_set_highlight(mbttag,1); } } catch(exception& ex) { //---- Enter your exception handling code here ----- dzbk::theUI->NXMessageBox()->Show("Block Styler", NXOpen::NXMessageBox::DialogTypeError, ex.what()); } } //------------------------------------------------------------------------------ //Callback Name: dialogShown_cb //This callback is executed just before the dialog launch. Thus any value set //here will take precedence and dialog will be launched showing that value. //------------------------------------------------------------------------------ void dzbk::dialogShown_cb() { try { //---- Enter your callback code here ----- } catch(exception& ex) { //---- Enter your exception handling code here ----- dzbk::theUI->NXMessageBox()->Show("Block Styler", NXOpen::NXMessageBox::DialogTypeError, ex.what()); } } //------------------------------------------------------------------------------ //Callback Name: apply_cb //------------------------------------------------------------------------------ int dzbk::apply_cb() { int errorCode = 0; try { double pyl = juli->Value(); // 圆柱面偏置量(用户输入) double chamferOffset = -0.03; // 沉头平面固定偏置-0.03 vector<NXOpen::TaggedObject *> gjt = gongju->GetSelectedObjects(); vector<NXOpen::TaggedObject *> mbt = mubiao->GetSelectedObjects(); // 存储原始目标体的所有面(求差前的面) std::set<tag_t> originalFaces; for(int a = 0; a < mbt.size(); a++) { tag_t mbttag = mbt[a]->Tag(); UF_DISP_set_highlight(mbttag,1); uf_list_p_t originalFaceList = NULL; UF_MODL_ask_body_faces(mbttag, &originalFaceList); int originalCount = 0; UF_MODL_ask_list_count(originalFaceList, &originalCount); for(int i = 0; i < originalCount; i++) { tag_t faceTag = NULL_TAG; UF_MODL_ask_list_item(originalFaceList, i, &faceTag); originalFaces.insert(faceTag); } UF_MODL_delete_list(&originalFaceList); } // 存储已经偏置过的面(避免重复偏置) std::set<tag_t> offsetFaces; for(int g = 0; g < gjt.size(); g++) { tag_t gjtTag = gjt[g]->Tag(); for(int a = 0; a < mbt.size(); a++) { tag_t mbttag = mbt[a]->Tag(); tag_t frec_eid = NULL_TAG; UF_MODL_subtract_bodies_with_retained_options(mbttag, gjtTag, 0, 1, &frec_eid); // 求差,保留工具体 UF_DISP_set_highlight(mbttag,0); // 获取求差后的面 uf_list_p_t faceList = NULL; UF_MODL_ask_body_faces(mbttag, &faceList); int listCount = 0; UF_MODL_ask_list_count(faceList, &listCount); for (int i = 0; i < listCount; i++) { tag_t faceTag = NULL_TAG; UF_MODL_ask_list_item(faceList, i, &faceTag); // 如果面是原始面或已经偏置过,则跳过 if(originalFaces.find(faceTag)!=originalFaces.end()||offsetFaces.find(faceTag)!=offsetFaces.end()) { continue; } int faceSubtype = 0; UF_MODL_ask_face_type(faceTag, &faceSubtype); // (1) 如果是圆柱面,按输入值偏置 if (faceSubtype == 16) // 16=圆柱面 { char offsetStr[32]; sprintf(offsetStr, "%f", pyl); uf_list_p_t faces = NULL; UF_MODL_create_list(&faces); UF_MODL_put_list_item(faces, faceTag); tag_t feature_obj_id = NULL_TAG; UF_MODL_create_face_offset(offsetStr, faces, &feature_obj_id); UF_MODL_delete_list(&faces); offsetFaces.insert(faceTag); // 标记为已偏置 } // (2) 如果是平面(沉头面),额外偏置-0.03 else if (faceSubtype == 22) // 22=平面 { char offsetStr[32]; sprintf(offsetStr, "%f", chamferOffset); uf_list_p_t faces = NULL; UF_MODL_create_list(&faces); UF_MODL_put_list_item(faces, faceTag); tag_t feature_obj_id = NULL_TAG; UF_MODL_create_face_offset(offsetStr, faces, &feature_obj_id); UF_MODL_delete_list(&faces); offsetFaces.insert(faceTag); // 标记为已偏置 } } UF_MODL_delete_list(&faceList); } } } catch(exception& ex) { //---- Enter your exception handling code here ----- errorCode = 1; dzbk::theUI->NXMessageBox()->Show("Block Styler", NXOpen::NXMessageBox::DialogTypeError, ex.what()); } return errorCode; } //------------------------------------------------------------------------------ //Callback Name: update_cb //------------------------------------------------------------------------------ int dzbk::update_cb(NXOpen::BlockStyler::UIBlock* block) { try { if(block == mubiao) { //---------Enter your code here----------- } else if(block == gongju) { //---------Enter your code here----------- } else if(block == separator0) { //---------Enter your code here----------- } else if(block == separator01) { //---------Enter your code here----------- } else if(block == juli) { //---------Enter your code here----------- } } catch(exception& ex) { //---- Enter your exception handling code here ----- dzbk::theUI->NXMessageBox()->Show("Block Styler", NXOpen::NXMessageBox::DialogTypeError, ex.what()); } return 0; } //------------------------------------------------------------------------------ //Callback Name: ok_cb //------------------------------------------------------------------------------ int dzbk::ok_cb() { int errorCode = 0; try { errorCode = apply_cb(); } catch(exception& ex) { //---- Enter your exception handling code here ----- errorCode = 1; dzbk::theUI->NXMessageBox()->Show("Block Styler", NXOpen::NXMessageBox::DialogTypeError, ex.what()); } return errorCode; UF_terminate(); } //------------------------------------------------------------------------------ //Function Name: GetBlockProperties //Description: Returns the propertylist of the specified BlockID //------------------------------------------------------------------------------ PropertyList* dzbk::GetBlockProperties(const char *blockID) { return theDialog->GetBlockProperties(blockID); } 这是我的程序 将这个功能加进去
06-17
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值