私はこの例を本に持っていますが、私のpython 3.3では機能しません
x = 'item found'
def search():
raise x or return
try:
search()
except x:
print('exception')
else:
print('no exception')
理由を教えてもらえますか?
私はこの例を本に持っていますが、私のpython 3.3では機能しません
x = 'item found'
def search():
raise x or return
try:
search()
except x:
print('exception')
else:
print('no exception')
理由を教えてもらえますか?
Simple: return
is a statement, not an expression. Statements have to appear on their own line. raise
is a statement too, it expects it's expression to evaluate to an exception to raise, but neither x
nor the return
statement fulfills that.
As it stands, the line is complete nonsense. It is not valid Python.
What happens instead, is that the Python parser will flag this code as invalid and raise a SyntaxError
exception for the whole file. No code contained in the file will actually be run:
File "demo.py", line 4
raise x or return
^
SyntaxError: invalid syntax