Python基础教程——8 异常

第8章 异常

8.1 什么是异常

>>> 1/0

Traceback (most recent call last):
  File "<pyshell#0>", line 1, in <module>
    1/0
ZeroDivisionError: integer division or modulo by zero

8.2按自己的方式出错

8.2.1 raise语句
>>> raise Exception

Traceback (most recent call last):
  File "<pyshell#1>", line 1, in <module>
    raise Exception
Exception


>>> raise Exception('hyperdrive overload')

Traceback (most recent call last):
  File "<pyshell#2>", line 1, in <module>
    raise Exception('hyperdrive overload')
Exception: hyperdrive overload


>>> import exceptions
>>> dir(exceptions)
['ArithmeticError', 'AssertionError', 'AttributeError', 'BaseException', 'DeprecationWarning', 'EOFError', 'EnvironmentError', 'Exception', 'FloatingPointError', 'FutureWarning', 'GeneratorExit', 'IOError', 'ImportError', 'ImportWarning', 'IndentationError', 'IndexError', 'KeyError', 'KeyboardInterrupt', 'LookupError', 'MemoryError', 'NameError', 'NotImplementedError', 'OSError', 'OverflowError', 'PendingDeprecationWarning', 'ReferenceError', 'RuntimeError', 'RuntimeWarning', 'StandardError', 'StopIteration', 'SyntaxError', 'SyntaxWarning', 'SystemError', 'SystemExit', 'TabError', 'TypeError', 'UnboundLocalError', 'UnicodeDecodeError', 'UnicodeEncodeError', 'UnicodeError', 'UnicodeTranslateError', 'UnicodeWarning', 'UserWarning', 'ValueError', 'Warning', 'WindowsError', 'ZeroDivisionError', '__doc__', '__name__']

>>> raise ArithmeticError

Traceback (most recent call last):
  File "<pyshell#7>", line 1, in <module>
    raise ArithmeticError
ArithmeticError
>>>

8.3 捕捉异常

>>> try:
 x = input('Input the x: ')
 y = input('Input the y: ')
 print x/y
except ZeroDivisionError:
 print 'The second number should not be zero! '

Input the x: 10
Input the y: 0
The second number should not be zero!


>>> try:
 x = input('Input the x: ')
 y = input('Input the y: ')
 print x/y
except ZeroDivisionError:
 print 'The second number should not be zero! '

Input the x: 8
Input the y: 9
0

屏蔽除零错误

>>> class MuffledCalculator:
 muffled = False
 def calc(self,expr):
  try:
   return eval(expr)
  except ZeroDivisionError:
   if self.muffled:
    print 'Division by zero is illegal'
   else:
    raise

>>> calculator = MuffledCalculator()
>>> calculator.calc('10/2')
5
>>> calculator.calc('10/0')

Traceback (most recent call last):
  File "<pyshell#40>", line 1, in <module>
    calculator.calc('10/0')
  File "<pyshell#37>", line 5, in calc
    return eval(expr)
  File "<string>", line 1, in <module>
ZeroDivisionError: integer division or modulo by zero
>>> calculator.muffled = True
>>> calculator.calc('10/0')
Division by zero is illegal

如果捕捉到异常,但是又想重新引发它,也就是说要传递异常,那么可以调用不带参数的raise们还能在捕捉到异常时显式的提供具体异常

如果这个行为被激活,那么计算器就会打印错误信息,而不是让异常传播,如果在于用户交互的过程中,那么这就很有用了。

但是如果在程序内部使用,引发异常会更好些,因此屏蔽机制就可以关掉了。

8.4 不止一个except子句

>>> try:
 x = input('Input the x: ')
 y = input('Input the y: ')
 print x/y
except ZeroDivisionError:
 print 'The second number should not be zero! '
except TypeError:
 print 'That was not a number?!'

Input the x: 10
Input the y: 'Hi'
That was not a number?!

8.5 用一个块捕捉两个异常

>>> try:
 x = input('Input the x: ')
 y = input('Input the y: ')
 print x/y
except (ZeroDivisionError, TypeError, NameError):
 print 'Your numbers were bogus....'

Input the x: 8
Input the y: 0
Your numbers were bogus....


>>> try:
 x = input('Input the x: ')
 y = input('Input the y: ')
 print x/y
except (ZeroDivisionError, TypeError, NameError):
 print 'Your numbers were bogus....'

Input the x: 10
Input the y: 'Hi'
Your numbers were bogus....

8.6捕捉对象

>>> try:
 x = input('Input the x: ')
 y = input('Input the y: ')
 print x/y
except (ZeroDivisionError, TypeError),e:
 print e

Input the x: 10
Input the y: 0
integer division or modulo by zero
>>> e
ZeroDivisionError('integer division or modulo by zero',)
>>> try:
 x = input('Input the x: ')
 y = input('Input the y: ')
 print x/y
except (ZeroDivisionError, TypeError),e:
 print e

Input the x: 'Hello'
Input the y: 'world'
unsupported operand type(s) for /: 'str' and 'str'
>>> e
TypeError("unsupported operand type(s) for /: 'str' and 'str'",)

8.7真正的全捕捉

>>> try:
 x = input('Input the x: ')
 y = input('Input the y: ')
 print x/y
except :
 print 'Something was wrong...'

Input the x: 8
Input the y: 'haha'
Something was wrong...

8.8 完事大吉

>>> try:
 print 'A simple task.'
except:
 print 'What? Something was wrong?'
else:
 print 'Ah...It was as planned'

A simple task.
Ah...It was as planned

一直输入直到合法输入

>>> while True:
 try:
  x = input('Input the x: ')
         y = input('Input the y: ')
         value = x/y
         print 'x/y is',value
 except:
  print 'Invalid input.Please try again'
 else:
  break

Input the x: 8
Input the y: 0
Invalid input.Please try again
Input the x: 8
Input the y: '1'
Invalid input.Please try again
Input the x: 8
Input the y:
Invalid input.Please try again
Input the x: 9
Input the y: 2
x/y is 4

打印错误信息

>>> while True:
 try:
  x = input('Input the x: ')
         y = input('Input the y: ')
         value = x/y
         print 'x/y is',value
 except Exception , e:
  print 'Invlid input',e
  print 'Invalid input.Please try again'
 else:
  break

Input the x: 1
Input the y: 0
Invlid input integer division or modulo by zero
Invalid input.Please try again
Input the x: 4
Input the y: '2'
Invlid input unsupported operand type(s) for /: 'int' and 'str'
Invalid input.Please try again
Input the x: 3
Input the y:
Invlid input unexpected EOF while parsing (<string>, line 0)
Invalid input.Please try again
Input the x: 4
Input the y: 2
x/y is 2

 8.9 最后

>>> x = None
>>> try:
 x = 1/0
finally:
 print 'Cleaning up...'
 del x

Cleaning up...

Traceback (most recent call last):
  File "<pyshell#6>", line 2, in <module>
    x = 1/0
ZeroDivisionError: integer division or modulo by zero
>>>

>>> try:
 1/0
except NameError:
 print 'Unkown variable'
else:
 print 'It is ok.'
finally:
 print 'Cleaning up..'

Cleaning up..

Traceback (most recent call last):
  File "<pyshell#17>", line 2, in <module>
    1/0
ZeroDivisionError: integer division or modulo by zero
>>>

8.10 异常和函数

 def faulty():
    raise Exception('Something is wrong.')
def ignore_exception():
    faulty()
def handle_excepton():
    try:
        faulty()
    except:
        print 'Exception handled'
print 'ignore_exception()'
ignore_exception()

ignore_exception()

Traceback (most recent call last):
  File "F:/Python/8-1函数与异常.py", line 11, in <module>
    ignore_exception()
  File "F:/Python/8-1函数与异常.py", line 4, in ignore_exception
    faulty()
  File "F:/Python/8-1函数与异常.py", line 2, in faulty
    raise Exception('Something is wrong.')
Exception: Something is wrong.

>>> handle_exception()
Exception handled
>>>

8.11

>>> def describlePerson(person):
 print 'Description of ',person['name']
 print 'Age: ',person['age']
 try:
  print 'Occupation: '+person['occupation']
 except KeyError:
  pass

>>> person = {'name':'ABC','age':21}
>>> person
{'age': 21, 'name': 'ABC'}
>>> describlePerson(person)
Description of  ABC
Age:  21

猜你喜欢

转载自blog.csdn.net/mickey_miki/article/details/7844894
今日推荐