Exceptions | Sololearn: Learn to code for FREE!
Nouvelle formation ! Tous les codeurs devraient apprendre l'IA générative !
Essayez une leçon gratuite
+ 1


Why or when would you use a raise statement in python?

15th Apr 2024, 4:36 AM
Maxed Out
Maxed Out - avatar
2 Réponses
+ 3
One use case would be if you wrote a method that was only supposed to accept a certain value, but it wouldn’t know it had an invalid one if it didn’t check. That is, until it crashed or bugged much later and gave you an unhelpful error message. That kind of thing can happen a lot if the code is meant to be run indirectly, by someone else or even by you. Exceptions are for telling the user that something was coded wrong.
15th Apr 2024, 5:00 AM
Wilbur Jaywright
Wilbur Jaywright - avatar
+ 1
Maxed Out , Here's a special usage of raise. When you're setting up a try compound statement, and you're not sure which exceptions might be raised in the try clause, you can create a raw or naked except clause (normally a bad idea) as a stub to catch every exception during testing, and inside it, put a raise statement (which makes the naked except OK). In that context, raise re-raises whatever exception got caught, stopping the program and printing the error message so you can see it. Then you can add an explicit except clause for that exception, and continue testing. For example, start like this. try: pass # code that might fail except: raise # re-raise any exception Then if the above code catches a TypeError, you would add a clause for it as below, and continue testing, adding another clause for each exception you discover. try: pass # code that might fail except TypeError: pass # do whatever's appropriate except: raise # re-raise any other exception
15th Apr 2024, 5:05 PM
Rain - avatar