python-错误和异常

1.常见的错误

NameError

SyntaxError

IOError

ZeroDivisionError:10/0

ValueError:a=int('12ab')

2.try--except异常处理

#!/usr/bin/env python

import random

num = random.randint(0,100)

while True:
try:
guess = int(raw_input("Enter a number:"))
except ValueError,e:
print "Enter 1~100"
continue
if guess > num:
print "guess Bigger",guess
elif guess <num:
print "guess smaller",guess
else:
print "guess Ok ,game over"
break
print " "

3.with_as语句

with open('1.txt') as f:

  for line in f.readlines():

    print line

4.raise语句

raise语句用于主动抛出异常

语法格式:raise [exception[,args]]

exception: 异常类

raise TypeError "type error"

assert语句:

5.标准异常和自定义异常

class FileError(IOError):

  pass

raise FileError,"File Error"

try:

  raise FileError,"File Error"

except FileError,e:

  print e

原文地址:https://www.cnblogs.com/Nyan-Workflow-FC/p/5678854.html