Python基礎教程——8 異常__Python

來源:互聯網
上載者:User

第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

 

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.