Python advanced (25) – use try-except statement to catch and handle exceptions

Original link: https://chegva.com/5469.html

◎Knowledge points

  1. Catch and handle exceptions with try-except statements

◎Script practice

 """ When the program generates an exception during running, in order to allow the program to continue to run, the thrown exception instance object can be captured and processed. This is achieved with a try-except statement: Put the code that may generate an exception in a try block to catch the exception instance object, Put exception-handling code in an except block consisting of several except clauses.   The syntax of the try-except statement is: try: Code that may generate exception except exception class object 1: The current except clause handles the exception code except exception class object 2: The code that handles the exception in the current except clause... except exception class object n: The code that handles the exception in the current except clause"""  try: result = 1 / 2 # result = 1 / 0 # result = int('abc') print(result) except ImportError: print("Import error") except ZeroDivisionError: print("0 cannot be used as a divisor") except TypeError: print("Type error") print("End")  """ If the class object corresponding to the thrown exception instance object is a subclass of the exception class object in the except clause, the except clause will also be matched with """  try: result = 1 / 0 print(result) except ArithmeticError: print("Math error")  """ When an exception occurs in the try statement block, it will check whether there is a matching except clause from top to bottom. As long as a matching except clause is found, the remaining except clauses will not be searched. Therefore, pay attention to the order of each except clause """  try: result = 1 / 0 print(result) except ZeroDivisionError: print("0 cannot be used as a divisor") except ArithmeticError: print("Math error") print("End")  try: result = 1 / 0 print(result) except ArithmeticError: print("Math error") except ZeroDivisionError: print("0 cannot be used as a divisor") print("End")  """ When the exception handling codes corresponding to multiple exception class objects are exactly the same, these exception class objects can be placed in an except clause in the form of a tuple"""  try: result = 1 / 0 print(result) except TypeError: print("Error running") except ZeroDivisionError: print("Error running") except ValueError: print("Error running")  try: result = 1 / 0 print(result) except (TypeError, ZeroDivisionError, ValueError): print("Error running")  """ If you want to access the exception instance object in the matched except clause, you can add the keyword as and a variable to the colon in the except clause  """  try: result = 1 / 0 print(result) except ZeroDivisionError as err: print(type(err)) # <class 'ZeroDivisionError'> # The class object ZeroDivisionError implements the special method __str__() print(err) # division by zero  try: result = int('abc') print(result) except (TypeError, ZeroDivisionError, ValueError) as err: print(type(err)) # <class 'ValueError'> # The class object ValueError implements the special method __str__() print(err) # invalid literal for int() with base 10: 'abc'  """ In order to cover all exception objects as much as possible in the except block, you can specify the exception class object in the last except clause as Exception (both built-in exception class objects and custom exception class objects inherit from Exception) , or do not specify the exception class object """ in the last except clause  try: result = 1 / 0 print(result) except (TypeError, ValueError): print("Type error or value error") # except: except Exception: print("Other errors") 

try-except语句的执行流程.png

◎Script address: https://github.com/anzhihe/learning/blob/master/python/practise/learn-python/python_advanced/try_except.py

This article is reprinted from: https://chegva.com/5469.html
This site is for inclusion only, and the copyright belongs to the original author.

Leave a Comment