为什么此代码导致语法错误?为什么我不能抓住这个例外?
protected function RunQuery($sql) {
$pdo = $this->conn;
$stmt = $pdo->prepare($sql);
if($stmt) {
$stmt->execute($sql);
} else {
print_r("Unable to prepare the query");
}
catch(PDOException $e) {
print_r($e);
exit(0);
}
}
答案 0 :(得分:6)
在添加catch块之前,您需要有一个try块。您需要将代码更改为以下内容:
#views.py
import json
def get_city_names(request):
#what was in the question an array is now a python list of dicts.
#it can also be in some other file and just imported.
all_city_names = [
{ good_name: 'Mallorca', input_name: 'Palma de Mallorca' },
{ good_name: 'Mallorca', input_name: 'Mallorca' },
{ good_name: 'Mallorca', input_name: 'Majorca' },
# etc
]
if request.is_ajax():
q = request.GET.get('term', '')
city_names = [c['good_name'] for c in all_city_names if q in c["input_name"]]
city_names = set(city_names) #removing duplicates
results = []
for cn in city_names:
cn_json = {'value': cn}
results.append(cn_json)
data = json.dumps(results)
else:
data = 'fail'
mimetype = 'application/json'
return HttpResponse(data, mimetype)
有关try& amp ;;的更多信息可以在php documentation。
中找到catch以及如何处理异常答案 1 :(得分:-3)
好像你在上面的线上错过了一个'}'。