[关闭]
@Channelchan 2018-09-29T22:23:50.000000Z 字数 1699 阅读 78233

Python异常处理

1、 定位与调试

第几行?

什么错?

怎么改?

  1. price = 1
  2. if price>0:
  3. print ('True')
  4. print (price is greater than 0)
  5. else:
  6. print "False"
  File "<ipython-input-1-1d2f1bbcc104>", line 4
    print (price is greater than 0)
                               ^
SyntaxError: invalid syntax

以上报错代码显示第四行出现语法错误,是缩进错误。

  1. price=1
  2. if price>0:
  3. print ('True')
  4. print ('price is greater than 0')
  5. else:
  6. print "False"
  File "<ipython-input-2-cf69990590e3>", line 6
    print "False"
                ^
SyntaxError: Missing parentheses in call to 'print'

以上报错代码显示第六行出现语法错误,是少了括号。

  1. price=1
  2. if price>0:
  3. print ('True')
  4. print ('price is greater than 0')
  5. else:
  6. print ("False")
True
price is greater than 0

以上是正确修改后的代码,无需所有缩进都对齐,只需同级对齐。

2、 try/except

捕捉异常可以使用try/except语句。

try/except语句用来检测try语句块中的错误,从而让except语句捕获异常信息并处理。

如果你不想在异常发生时结束你的程序,只需在try里捕获它。

try:

正常的操作
......................

except:

发生异常,执行这块代码
......................

else:

如果没有异常执行这块代码
  1. # 定义函数
  2. def test_price(price):
  3. return int(price)
  4. # 调用函数
  5. test_price("z66")
---------------------------------------------------------------------------

ValueError                                Traceback (most recent call last)

<ipython-input-6-3de6ec1555dc> in <module>()
      3     return int(price)
      4 # 调用函数
----> 5 test_price("z66")


<ipython-input-6-3de6ec1555dc> in test_price(price)
      1 # 定义函数
      2 def test_price(price):
----> 3     return int(price)
      4 # 调用函数
      5 test_price("z66")


ValueError: invalid literal for int() with base 10: 'z66'
  1. # 定义函数
  2. def test_price(price):
  3. try:
  4. p = int(price)
  5. except ValueError:
  6. print ("参数不是数字")
  7. else:
  8. print(p+100)
  9. finally:
  10. print('Go on')
  11. # 调用函数
  12. test_price("z66")
参数不是数字
Go on

3、 Raise

  1. def check_price(price):
  2. if price < 0:
  3. raise Exception("Invalid price!", price)
  4. # 触发异常后,后面的代码就不会再执行
  5. try:
  6. check_price(-1)
  7. print('right')
  8. ##触发异常
  9. except Exception as e:
  10. print (e)
  11. else:
  12. print ('can_trade')
('Invalid price!', -1)

4、 常见报错类型

SyntaxError Python | 语法错误

TypeError | 对类型无效的操作

NameError | 未声明/初始化对象 (没有属性)

ValueError | 传入无效的参数

ImportError | 导入模块/对象失败

查看更多: http://www.runoob.com/python/python-exceptions.html

添加新批注
在作者公开此批注前,只有你和作者可见。
回复批注