dream07769 2015-06-05 03:41
浏览 51
已采纳

在Golang中导入模块时如何捕获错误?

In golang, when I import a module, its init() gets executed (before main() I assume?), it is possible some error is generated in this function. How can I capture these errors and handle them in my own code?

  • 写回答

3条回答 默认 最新

  • dpv21589 2015-06-05 05:37
    关注

    Yes, package init() functions run before the main() function, see Package initialization in the language specification.

    And no, you can't handle errors occurred in package init() functions. Even if you could, that would mean a package your program depends on failed to initialize and you wouldn't know what to expect from it.

    Package init() functions have no return values and they can't panic in a meaningful way that was meant to recover from. If an init() function panics, the program terminates.

    Since init() functions are not called by you (e.g. from the main() function), you can't recover from there. It is the responsibility of the package itself to handle errors during its initialization, not the users of the package.

    One option to signal error happening during an init() is to store the error state in a variable (e.g. exported, or unexported but queryable by an exported function). But this should be used only if it is reasonable to continue, and this is also the task/responsibility of the package itself (to store/report the error) and not the users of the package. You can't do this without the cooperation of the package (you can't "catch" unhandled/unreported errors and panics).

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?

悬赏问题

  • ¥15 基于卷积神经网络的声纹识别
  • ¥15 Python中的request,如何使用ssr节点,通过代理requests网页。本人在泰国,需要用大陆ip才能玩网页游戏,合法合规。
  • ¥100 为什么这个恒流源电路不能恒流?
  • ¥15 有偿求跨组件数据流路径图
  • ¥15 写一个方法checkPerson,入参实体类Person,出参布尔值
  • ¥15 我想咨询一下路面纹理三维点云数据处理的一些问题,上传的坐标文件里是怎么对无序点进行编号的,以及xy坐标在处理的时候是进行整体模型分片处理的吗
  • ¥15 CSAPPattacklab
  • ¥15 一直显示正在等待HID—ISP
  • ¥15 Python turtle 画图
  • ¥15 stm32开发clion时遇到的编译问题