Python Forum
if condition inside try / except -- how to?? - Printable Version

+- Python Forum (https://python-forum.io)
+-- Forum: Python Coding (https://python-forum.io/forum-7.html)
+--- Forum: General Coding Help (https://python-forum.io/forum-8.html)
+--- Thread: if condition inside try / except -- how to?? (/thread-21515.html)



if condition inside try / except -- how to?? - ridgerunnersjw - Oct-02-2019

Good afternoon...
Can someone please show me what I am missing. Basically I want to take an argument in and check if it exists within a tuple of valid arguments. If it does GREAT, if not raise an error that tells the user to try again.....

_SCOPE_VARIABLES = ('open', 'read', 'write', 'query', 'close')

class command:
	def __init__(self, command, scope = 'NONE', **kwargs):
		self.command = command
		self.scope = scope
		try:
			self.scope in _SCOPE_VARIABLES
		except:
			print ('Try again')


Thanks


RE: if condition inside try / except -- how to?? - micseydel - Oct-02-2019

It sounds like you want to throw (raise) an exception, not catch (try/except) one. Just have an if block based on your condition and raise an exception from within the block.

By the way, it's weird that you have a default argument for scope which would result in an exception. It would probably be better to just require clients provide their own argument.