Sm Has Thown A Generic Pyton Exception
Bdb — Debugger framework¶ The bdb module handles basic debugger functions, like setting breakpoints or managing execution via the debugger. The following exception is defined: exception bdb.BdbQuit¶ Exception raised by the Bdb class for quitting the debugger. The bdb module also defines two classes: class bdb. Try block is used to enclose the code that might throw an exception. Try block must be followed by either catch or finally block. Catch block is used to handle the exception thrown with in a try block. There can't be any code between the end of the try block and the beginning of the first catch block.
I have this try block in my code: try:dosomethingthatmightraiseanexceptionexcept ValueError as err:errmsg = 'My custom error message.' Raise ValueError(errmsg)Strictly speaking, I am actually raising another ValueError, not the ValueError thrown by dosomething., which is referred to as err in this case.
How do I attach a custom message to err? I try the following code but fails due to err, a ValueError instance, not being callable: try:dosomethingthatmightraiseanexceptionexcept ValueError as err:errmsg = 'My custom error message.' Raise err(errmsg). Update: For Python 3, checkTo attach a message to the current exception and re-raise it:(the outer try/except is just to show the effect)For python 2.x where x=6: try:try:raise ValueError # something bad.except ValueError as err:err.message=err.message+' hello'raise # re-raise current exceptionexcept ValueError as e:print(' got error of type '+ str(type(e))+' with message ' +e.message)This will also do the right thing if err is derived from ValueError. For example UnicodeDecodeError.Note that you can add whatever you like to err. For example err.problematicarray=1,2,3.Edit: @Ducan points in a comment the above does not work with python 3 since.message is not a member of ValueError. Instead you could use this (valid python 2.6 or later or 3.x): try:try:raise ValueErrorexcept ValueError as err:if not err.args:err.args=(',)err.args = err.args + ('hello',)raiseexcept ValueError as e:print(' error was '+ str(type(e))+str(e.args))Edit2:Depending on what the purpose is, you can also opt for adding the extra information under your own variable name.
Sm Has Thrown A Generic Python Exception
For both python2 and python3: try:try:raise ValueErrorexcept ValueError as err:err.extrainfo = 'hello'raiseexcept ValueError as e:print(' error was '+ str(type(e))+str(e))if 'extrainfo' in dir(e):print e.extrainfo. Unfortunately there's no guarantee that args0 is a string type representing an error message - 'The tuple of arguments given to the exception constructor. Some built-in exceptions (like IOError) expect a certain number of arguments and assign a special meaning to the elements of this tuple, while others are usually called only with a single string giving an error message.' So the code won't work arg0 is not an error message (it could be an int, or it could be a string representing a file name).–Nov 1 '13 at 5:29. A real example of when args0 isn't an error message -'exception EnvironmentError The base class for exceptions that can occur outside the Python system: IOError, OSError. When exceptions of this type are created with a 2-tuple, the first item is available on the instance’s errno attribute (it is assumed to be an error number), and the second item is available on the strerror attribute (it is usually the associated error message).
The tuple itself is also available on the args attribute.' –Nov 5 '13 at 22:51. I realize this question has been around for awhile, but once you're lucky enough to only support python 3.x, this really becomes a thing of beauty:) raise fromWe can chain the exceptions using. Try:1 / 0except ZeroDivisionError as e:raise Exception('Smelly socks') from eIn this case, the exception your caller would catch has the line number of the place where we raise our exception. Traceback (most recent call last):File 'test.py', line 2, in 1 / 0ZeroDivisionError: division by zeroThe above exception was the direct cause of the following exception:Traceback (most recent call last):File 'test.py', line 4, in raise Exception('Smelly socks') from eException: Smelly socksNotice the bottom exception only has the stacktrace from where we raised our exception. Your caller could still get the original exception by accessing the cause attribute of the exception they catch. WithtracebackOr you can use.
Try:1 / 0except ZeroDivisionError as e:raise Exception('Smelly socks').withtraceback(e.traceback)Using this form, the exception your caller would catch has the traceback from where the original error occurred. Traceback (most recent call last):File 'test.py', line 2, in 1 / 0ZeroDivisionError: division by zeroDuring handling of the above exception, another exception occurred:Traceback (most recent call last):File 'test.py', line 4, in raise Exception('Smelly socks').withtraceback(e.traceback)File 'test.py', line 2, in 1 / 0Exception: Smelly socksNotice the bottom exception has the line where we performed the invalid division as well as the line where we reraise the exception. Re-raising a new exception or chain raising exceptions with new messages creates more confusion than needed in many cases. By itself exceptions are complex to handle.
Python Generic Exception Handling
A better strategy is to just append your message to the argument of the original exception if possible as in err.args += ('message',) and re-raise the exception message. The traceback might not take you to the line numbers where the exception was caught but it will take you to where the exception occurred for sure.–Jan 26 '18 at 23:53. It seems all the answers are adding info to e.args0, thereby altering the existing error message. Is there a downside to extending the args tuple instead? I think the possible upside is, you can leave the original error message alone for cases where parsing that string is needed; and you could add multiple elements to the tuple if your custom error handling produced several messages or error codes, for cases where the traceback would be parsed programmatically (like via a system monitoring tool). This is the function I use to modify the exception message in Python 2.7 and 3.x while preserving the original traceback.
This is a great answer. But I still work with a lot of 2.7 code, and I often find myself wanting to add information to an unexpected exception, like an input file position or the values of some variables, but keep the original stack and exception. I can log it, but sometimes I don't want it logged, e.g. If parent code ultimately handles it. Raise sys.excinfo0, (sys.excinfo1, myextrainfo), sys.excinfo2 seems to do what I want, and I've never run into problems with it.
But it feels hacky, and not an accepted practice. Is there a better way?–Mar 15 '17 at 20:40. In Python3 there are 4 different syntaxes for rasing exceptions: 1. Raise exception2. Raise exception (args)3.
Raise exception (args) from originalexception1. Raise exception vs. Raise exception (args)If you use raise exception (args) to raise an exception then the args will be printed when you print the exception object - as shown in the example below. #raise exception (args)try:raise ValueError('I have raised an Exception')except ValueError as exp:print ('Error', exp) # Output - Error I have raised an Exception#raise execptiontry:raise ValueErrorexcept ValueError as exp:print ('Error', exp) # Output - Error3.raiseraise statement without any arguments re-raises the last exception.This is useful if you need to perform some actions after catching the exception and then want to re-raise it.
But if there was no exception before, raise statement raises TypeError Exception. Def somefunction:print('some cleaning')a=10b=0result=Nonetry:result=a/bprint(result)except Exception: #Output -somefunction #some cleaningraise #Traceback (most recent call last):#File 'python', line 8, in #ZeroDivisionError: division by zero4.
Raise exception (args) from originalexceptionThis statement is used to create exception chaining in which an exception that is raised in response to another exception can contain the details of the original exception - as shown in the example below. Class MyCustomException(Exception):passa=10b=0reuslt=Nonetry:try:result=a/bexcept ZeroDivisionError as exp:print('ZeroDivisionError - ',exp)raise MyCustomException('Zero Division ') from expexcept MyCustomException as exp:print('MyException',exp)print(exp.cause)Output: ZeroDivisionError - division by zeroMyException Zero Divisiondivision by zero.