'Throwing warnings' from my code

爷,独闯天下 提交于 2021-01-27 03:58:02

问题


I am writing a tool that processes some files. This tool will have a command-line interface but can also be used as a class library from third-party code. To deal with an error, I just throw an exception. Third-party code can handle the exception, and the command-line interface might just print it and abort. However, apart from fatal errors, it is also possible that a situation arises that is not fatal and the process can continue, for which I would like to 'throw a warning' and continue.

How do I deal with warnings, in such way that both third-party code and the command-line interface can do something with it?


回答1:


You throw an exception for this as well (assuming the error condition is indeed exceptional - that is expected to be rare).

Exceptions are not always lethal - you need to throw a specific type of exception that the third party code and command line code can catch and act on.

One rule of exception handling is to handle exceptions you know how to handle - if you have a specific exception type for the error and you document it, client code should know how to deal with it (or not).


If what you are trying to do is provide information to using code - warnings that are handled within your library already but that the users may want to know - you can output traces using the tracing subsystem. All users will need to do is configure a listener and will be able to get the information during runtime.




回答2:


I would suggest you not to throw an exception, they should be avoided if possible (they are resources costly). Instead you can create an event and raise it. Third party code and command-line interface will just need to sign to this event.



来源:https://stackoverflow.com/questions/12439811/throwing-warnings-from-my-code

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!