简体   繁体   中英

How to find what exceptions might be raised

I'm trying to find the best way of finding out what exceptions might be raised by my python code, what is the best method you guys use?

So far I can:

  1. pray is says it in the online docs somewhere (it rarely does.)
  2. scrape the .py files for raise statements...

There has to be better ways of getting this information!

This question was asked before(6 years ago), they did NOT get any answers though.

The general concensus seems to be, only catch exceptions that you think you need to catch, but I only know what exceptions I might need to catch by knowing what exceptions might be thrown in the first place... so I can't accept that as an answer. If your code is going to throw exceptions...surely there should be something in place for the users of your code to know what those exceptions are.

Any advice you guys can give me is very much appreciated!

There is a way to catch ALL of the exceptions, except this usually frowned upon. The best way to figure out is to write some tests for your program. Each program will throw different exceptions based on what its doing, as I'm sure you already know. So just test, test, and test some more.

The answer is not only in the function you call but in the code you write.

If your code always send valid argument it will never raise Exception, thus there is nothing to catch.

However your code might totally mess up and even cause exception that were not expected by the original developer. eg sending customized class or input type.

My recommendation is that very few exception needs to be catch unless you intended to trigger them.

In this respect, you example is very relevant:

If you hard code a string re.compile() will never fail...Jobs done ! But if you send dynamic regex, ( generated programmatically or collected from user input) then your code will have to deal with incorrect regex and process related exceptions.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM