# 该实例演示完整语法格式>>>whileTrue:try:
x =int(input("Please enter a number: "))breakexcept ValueError:print("Oops! That was no valid number. Try again ")
# 最后一个 except 子句可以忽略异常的名称,它将被当作通配符使用import sys
try:
f =open('myfile.txt')
s = f.readline()
i =int(s.strip())except OSError as err:print("OS error: {0}".format(err))except ValueError:print("Could not convert data to an integer.")except:print("Unexpected error:", sys.exc_info()[0])raise
try 语句有一个可选的 else 子句,它定义了 在 try 子句没有发生任何异常的时候执行
for arg in sys.argv[1:]:try:
f =open(arg,'r')except IOError:print('cannot open', arg)else:print(arg,'has',len(f.readlines()),'lines')
f.close()
>>>def this_fails():
x =1/0>>>try:
this_fails()except ZeroDivisionError as err:print('Handling run-time error:', err)
Handling run-time error:int division or modulo by zero
>>>classMyError(Exception):def__init__(self, value):
self.value = value
def__str__(self):returnrepr(self.value)>>>try:raise MyError(2*2)except MyError as e:print('My exception occurred, value:', e.value)
My exception occurred, value:4>>>raise MyError('oops!')
Traceback (most recent call last):
File "<stdin>", line 1,in ?
__main__.MyError:'oops!'
当创建一个模块 有可能抛出多种不同的异常时 ,一种通常的做法是 为这个包建立一个基础异常类
基于这个基础类为不同的错误情况创建不同的子类,大多数的异常的名字都以 Error 结尾
classError(Exception):"""Base class for exceptions in this module."""passclassInputError(Error):"""Exception raised for errors in the input.
Attributes:
expression -- input expression in which the error occurred
message -- explanation of the error
"""def__init__(self, expression, message):
self.expression = expression
self.message = message
classTransitionError(Error):"""Raised when an operation attempts a state transition that's not
allowed.
Attributes:
previous -- state at beginning of transition
next -- attempted new state
message -- explanation of why the specific transition is not allowed
"""def__init__(self, previous,next, message):
self.previous = previous
self.next=next
self.message = message