Sm Has Thown A Generic Pyton Exception

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.

Sm Has Thown A Generic Pyton ExceptionSm Has Thown A Generic Pyton ExceptionPython

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. 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.'

Sm Has Thrown A Generic Python Exception

–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. 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?

Python Generic Exception Handling

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.

Comments are closed.