Home >Backend Development >Python Tutorial >Analysis of exception handling examples in 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()Exception class It can only be used to handle specified exceptions. Non-specified exceptions cannot be handled.
s1 = 'hello' try: int(s1) except IndexError as e: # 未捕获到异常,程序直接报错 print(e)2. Multi-branch exception except..except and universal exception: Exception
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()4. The final execution of exceptions finallytry-finally statement will execute the final code regardless of whether an exception occurs. Define cleanup behavior:
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'#This module will be executed regardless of exception or not, usually Carry out cleanup work4. Throw an exception raisePython uses the raise statement to throw a specified exception. The syntax format of raise is as follows:
raise [Exception [, args [, traceback]]]
try: raise TypeError('抛出异常,类型错误') except Exception as e: print(e)raise The only parameter specifies the exception to be thrown. It must be an exception instance or an exception class (that is, a subclass of Exception). If you just want to know if this threw an exception and don't want to handle it, then a simple raise statement can throw it again.
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: HiThere5. Custom exceptionsYou can have your own exceptions by creating a new exception class. The exception class inherits from the Exception class, either directly or indirectly, for example: In this example, the default __init__() of the Exception class is overridden.
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) #抛出异常,类型错误Basic Exception ClassWhen creating a module that may throw many different exceptions, a common approach is to create a basic exception class for this package, and then based on this foundation The class creates different subclasses for different error conditions:Most exception names end with "Error", just like standard exception naming.
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 = message6. Assertassert (assert) is used to judge an expression and trigger an exception when the expression condition is false. Assertions can directly return an error when the conditions are not met for the program to run, without having to wait for the program to crash after running. The syntax format is as follows:
assert expressionis equivalent to:
if not expression: raise AssertionErrorassert can also be followed by parameters:
assert expression [, arguments]is equivalent to:
if not expression: raise AssertionError(arguments)The following example determines whether the current system is Linux. If the conditions are not met, an exception will be triggered directly without executing the next code:
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 下执行
The above is the detailed content of Analysis of exception handling examples in Python. For more information, please follow other related articles on the PHP Chinese website!