I have a hard time figuring this one out, it’s about mistakes that can be done when raising an exception in Python 2.7:
try:
raise [1, 2, 3, 4]
except Exception as ex:
print ex
the message here is “exceptions must be old-style classes or derived from BaseException, not list” – This part is ok, but when I change it to tuple, I am getting confused:
try:
raise (1, 2, 3, 4)
except Exception as ex:
print ex
the message here is “exceptions must be old-style classes or derived from BaseException, not int” – why is it interpreted as raising an int, not a tuple?
Futhermore:
try:
raise (Exception, 'a message')
except Exception as ex:
print ex
Here we are actually rising an Exception (consistent behaviour when compared with previous example, where we were raising an int) – I briefly thought that this is just an alternate way for this:
try:
raise Exception, 'a message'
except Exception as ex:
print ex
But in this case, ‘a message’ is being passed to Exceptions ctor (as documented on docs.python.org)
Can someone explain the 2nd and 3rd cases, and possible point me to code in interpreter that is responsible for this?
As documented in the Python 2 reference, the
raisestatement takes up to 3 expressions to create the exception being raised:If the first expression is a tuple, python will ‘unwrap’ the tuple recursively, taking the first element until it finds something other than a tuple. This behavior is being removed from Python 3 (see PEP 3109). The following is legal:
The documentation explains the rest in more detail, but the raise statement expects the first value to be a Exception class, the second value is seen as the value of the exception (the message) and the third value is a traceback. Python fills in
Nonefor the latter two values if missing.If the first value is a instance instead, the second value must be None:
If you use a tuple of more than 3 items, it’ll raise a syntax error:
In your case however, you raised neither a class nor an instance, so that’s what Python found to be incorrect first; if I use a string it’ll complain too:
The correct syntax is of course: