Is it bad form to raise ArgumentError by hand?

一笑奈何 提交于 2019-12-10 01:28:37

问题


If you want to add an extra check not provided by argparse, such as:

if variable a == b then c should be not None 

...is it permissible to raise ArgumentError yourself?

Or, should you raise Exception instead?

Also what is common practice for this kind of situation? Say that you add a piece of code that's almost like a local extension of the library. Should you use the same exception type(s) as those provided by the library you are extending?


回答1:


There's nothing inherently wrong with raising an ArgumentError. You can use it anytime the arguments you receive are not what you expected them to be, including checking range of numbers.

Also, yes, in general it's alright for you to use the same exceptions provided by a given library if you are writing an extension to that library.

Regarding raising Exceptions, I wouldn't do that. You should always raise a specific exception so you know how to handle it in the code. Catching Exception objects should be done at the highest level in your application, to catch and log all exceptions that you missed.



来源:https://stackoverflow.com/questions/8293325/is-it-bad-form-to-raise-argumenterror-by-hand

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