Python Try Except Throw 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
Python Exception Stack Trace
this site About Us Learn more about Stack Overflow the company Business python print exception Learn more about hiring developers or posting ads with us Stack Overflow Questions Jobs Documentation Tags Users Badges Ask python try without except Question x Dismiss Join the Stack Overflow Community Stack Overflow is a community of 6.2 million programmers, just like you, helping each other. Join them; it only takes a minute: Sign up https://docs.python.org/2.7/tutorial/errors.html Manually raising (throwing) an exception in Python up vote 800 down vote favorite 189 How can I raise an exception in 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 http://stackoverflow.com/questions/2052390/manually-raising-throwing-an-exception-in-python 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, 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 "
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 http://stackoverflow.com/questions/12724087/pythonic-way-of-raising-an-error-within-the-try-block Overflow the company Business Learn more about hiring developers or posting ads with us Stack Overflow Questions Jobs Documentation Tags Users Badges Ask Question x Dismiss Join the Stack Overflow Community Stack Overflow is a community http://www.python-course.eu/exception_handling.php of 6.2 million programmers, just like you, helping each other. Join them; it only takes a minute: Sign up pythonic way of raising an error within the try block up vote 1 down vote favorite I python exception have a method that checks something and which can raise an exception itself return True return False I want catch the exception properly to raise one myself, but also if the test returns False. The incorrect way to do this is try: if not check(): raise MyException() except: raise MyException() as the first MyException is caught after the except again. One way to handle this properly would be try: flag = python try except check() except: raise MyException() else: if not flag: raise MyException() Is this the only way of dealing with this situation, or is there another way to handle it more efficient, getting rid of the flag variable? python exception-handling try-catch share|improve this question asked Oct 4 '12 at 9:19 Alex 7,7431767134 3 First of all: don't use blanket except: catching, always only catch specific exceptions. –Martijn Pieters♦ Oct 4 '12 at 9:23 @avasal: what makes you think the OP doesn't know about raise? –Martijn Pieters♦ Oct 4 '12 at 9:23 You should add what Exception is raised in check(), because as you can see from the answers: there are a few ways to do this. –Sebastian Blask Oct 4 '12 at 9:48 yes, always except for a specific exception in the normal case. But when you run something on a server, you don't want the server stop because of an error, you want to propagate ANY error to the client. –Alex Oct 4 '12 at 11:52 add a comment| 3 Answers 3 active oldest votes up vote 3 down vote accepted You should never use except: because that catches ALL exceptions, including SystemExit, you should probably do: try: if not check(): raise MyNewException() except ExceptionRaisedByCheck: raise MyNewException()
and VariablesOperatorsinput and raw_input via the keyboardConditional StatementsWhile LoopsFor LoopsFormatted outputOutput with PrintSequential Data TypesDictionariesSets and Frozen SetsShallow and Deep CopyFunctionsRecursion and Recursive FunctionsTests, DocTests, UnitTestsMemoization with DecoratorsPassing ArgumentsNamespacesGlobal vs. Local VariablesFile ManagementModular Programming and ModulesIntroduction in Regular ExpressionsRegular Expressions, AdvancedLambda Operator, Filter, Reduce and MapList ComprehensionGeneratorsException HandlingObject Oriented ProgrammingInheritance ExampleSlotsClasses and Class CreationRoad to MetaclassesMetaclassesMetaclass Example: Count Function Calls Exception from the Rule "There are two great rules of life, the one general and the other particular. The first is that everyone can in the end, get what he wants, if he only tries. That is the general rule. The particular rule is that every individual is, more or less, an exception to the rule." Samuel Butler Delicate Handling "The finest qualities of our nature, like the bloom on fruits, can be preserved only by the most delicate handling. Yet we do not treat ourselves nor one another thus tenderly." Henry David Thoreau Supported by: Python Training Courses in Canada This topic in German / Deutsche Übersetzung: AusnahmebehandlungPython 2.7This tutorial deals with Python Version 2.7This chapter from our course is available in a version for Python3: Exception HandlingClassroom Training Courses This website contains a free and extensive online tutorial by Bernd Klein. If you are interested in an instructor-led classroom training in Canada or the US, you may have a look at the Python courses by Bernd Klein at Bodenseo © kabliczech - Fotolia.com Overview of Python courses by Bernd Klein. The Truth in Errors "The first step towards amendment is the recognition of error." Seneca "The world always makes the assumption that the exposure of an error is identical with the discovery of truth - that the error and truth are simply opposite. They are nothing of the sort. What the world turns to, when it is cured of one error, is usually simply another error, and maybe one worse than the first one." H.L. Mencken "Great services are not canceled by one act or by one single error." Benjamin Disraeli
Previous Chapter: Generators Next Chapter: Object Oriented Programming Exception Handling An exception is an error that happens during the execution of a program. Exceptions are known to non-programmers a