Python Trigger Error
Contents |
here for a quick overview of the site Help Center Detailed answers to any questions you might have Meta Discuss the workings and policies of this site About Us Learn more about Stack Overflow the company
Python Error Types
Business Learn more about hiring developers or posting ads with us Stack Overflow Questions python raise valueerror Jobs Documentation Tags Users Badges Ask Question x Dismiss Join the Stack Overflow Community Stack Overflow is a community of 6.2 million
Custom Exception Python
programmers, just like you, helping each other. Join them; it only takes a minute: Sign up Manually raising (throwing) an exception in Python up vote 800 down vote favorite 189 How can I raise an exception in syntax for generic except clause in python Python so that it can later be caught via an except block? python exception exception-handling share|improve this question edited Feb 3 '15 at 14:37 DavidRR 5,20472747 asked Jan 12 '10 at 21:07 TIMEX 41.2k201525826 add a comment| 3 Answers 3 active oldest votes up vote 787 down vote accepted How do I manually throw/raise an exception in Python? Use the most specific Exception constructor that semantically fits your issue. Be specific in your message, python throw error and exit e.g.: raise ValueError('A very specific bad thing happened') Don't do this: Avoid raising a generic Exception, to catch it, you'll have to catch all other more specific exceptions that subclass it. Hiding bugs raise Exception('I know Python!') # don't, if you catch, likely to hide bugs. For example: def demo_bad_catch(): try: raise ValueError('represents a hidden bug, do not catch this') raise Exception('This is the exception you expect to handle') except Exception as error: print('caught this error: ' + repr(error)) >>> demo_bad_catch() caught this error: ValueError('represents a hidden bug, do not catch this',) Won't catch and more specific catches won't catch the general exception: def demo_no_catch(): try: raise Exception('general exceptions not caught by specific handling') except ValueError as e: print('we will not catch e') >>> demo_no_catch() Traceback (most recent call last): File "