在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('无论异常与否,都会执行该模块,通常是进行清理工作')#invalid literal for int() with base 10: 'hello'#無論異常與否,都會執行該模組,通常是進行清理工作四、拋出例外raisePython 使用raise 語句拋出一個指定的例外。 raise語法格式如下:
raise [Exception [, args [, traceback]]]
try: raise TypeError('抛出异常,类型错误') except Exception as e: print(e)raise 唯一的一個參數指定了要被拋出的例外。它必須是一個異常的實例或是異常的類別(也就是 Exception 的子類別)。 如果你只想知道這是否拋出了一個異常,並不想去處理它,那麼一個簡單的 raise 語句就可以再次把它拋出。
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 AssertionErrorassert 後面也可以緊接參數:
assert expression [, arguments]等價於:
if not expression: raise AssertionError(arguments)以下實例判斷目前系統是否為Linux,如果不滿足條件則直接觸發異常,不必執行接下來的程式碼:###
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中文網其他相關文章!