在python中,錯誤觸發的例外如下
#二、異常的種類
# TypeError:int类型不可迭代 for i in 3: pass # ValueError num=input(">>: ") #输入hello int(num) # NameError aaa # IndexError l=['egon','aa'] l[3] # KeyError dic={'name':'egon'} dic['age'] # AttributeError class Foo:pass Foo.x # ZeroDivisionError:无法完成计算 res1=1/0 res2=1+'str'
try: 被检测的代码块 except 异常类型: try中一旦检测到异常,就执行这个位置的逻辑
try: f = [ 'a', 'a', 'a','a','a', 'a','a',] g = (line.strip() for line in f) #元组推导式 print(next(g)) print(next(g)) print(next(g)) print(next(g)) print(next(g)) except StopIteration: f.close()
s1 = 'hello' try: int(s1) except IndexError as e: # 未捕获到异常,程序直接报错 print(e)
s1 = 'hello' try: int(s1) except IndexError as e: print(e) except KeyError as e: print(e) except ValueError as e: print(e) except Exception as e: print(e)
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()
s1 = 'hello' try: int(s1) except IndexError as e: print(e) except KeyError as e: print(e) except ValueError as e: print(e) #except Exception as e: # print(e) else: print('try内代码块没有异常则执行我') finally: print('无论异常与否,都会执行该模块,通常是进行清理工作')
raise [Exception [, args [, traceback]]]
try: raise TypeError('抛出异常,类型错误') except Exception as e: print(e)
try: raise NameError('HiThere') except NameError: print('An exception flew by!') raise #An exception flew by! #Traceback (most recent call last): # File "", line 2, in ? #NameError: HiThere
class EgonException(Exception): def __init__(self, msg): self.msg = msg def __str__(self): return self.msg try: raise EgonException('抛出异常,类型错误') except EgonException as e: print(e) #抛出异常,类型错误
class Error(Exception): """Base class for exceptions in this module.""" pass class InputError(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 class TransitionError(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
assert expression
if not expression: raise AssertionError
assert expression [, arguments]
if not expression: raise AssertionError(arguments)
import sys assert ('linux' in sys.platform), "该代码只能在 Linux 下执行" # 接下来要执行的代码 # Traceback (most recent call last): # File "C:/PycharmProjects/untitled/run.py", line 2, in # assert ('linux' in sys.platform), "该代码只能在 Linux 下执行" # AssertionError: 该代码只能在 Linux 下执行
以上是Python中的異常處理實例分析的詳細內容。更多資訊請關注PHP中文網其他相關文章!