python--exceptions (built-in exceptions and application scenarios)

Source: Internet
Author: User

"" "What is an exception: 1, the exception points out that our program has error 2, some exceptions will also occur in some legitimate cases, such as the user name password error, the bank card number does not exist 3, the name of the built-in exception is the end of the error: Zerodivisionerror,indexerror, SyntaxError4, all exception classes are inherited from exception, (extended Baseexception) 5, when an exception occurs, the execution of the program will be stopped immediately, unless the exception is handled correctly 6, the exception is an object, And can inherit (by inheriting the exception class to implement its own exception) "" "" "# print " Hello "#抛出异常信息: syntaxerror: missing parentheses  in call to  ' print '.  did you mean print ("Hello")? #产生的SyntaxError异常, This is the exception for the exception, syntax error #x = 5 / 0#print (x) #抛出ZeroDivisionError异常, information: zerodivisionerror: division  by zero, said to be unable to be removed # lst = [1,2,3]# print (lst[3]) #抛出异常:indexerror: list  index out of range  says the index error # constructs the exception object through the built-in TypeError and ValueError classes, the following example expands the built-in list, and re-wrote the Append method within the Class mylist (list):  #继承内置的list类     def append (self,  Integer):         if not isinstance (Integer, int):  #如果不是整数则抛出异常              raise typeerror ("Not an integer")          if integer % 2:             raise valueerror ("can not be divisible")   #不能整除时则抛出异常          super (). Append (integer)   #调用父类的append方法 # mylist =  MyList () #  #mylist. Append (12.45)   #引发TypeError异常 #  #mylist. Append   #引发ValueError异常 #  Mylist.append   #无异常 # What is the program like when an exception occurs? Def test_return ():     print ("Hello")   #这条是会被执行的     raise  exception ("My god, something went wrong")   #这里引发异常后, the following code will never be executed, including the return statement      print ("How are you?")     return  "I ' M very good" #test_return () #通过另外一个函数来调用test_return函数 to see the effect def  call_test_return ():    Print ("Start call ...")     test_return ()   #在这里调用test_return函数      print ("an exception was raised ...")     print ("So ...") #call_test_ Return () "" "calls the Test_return function in the Call_test_return function, there is an exception in the Test_return function but there is no exception statement for the Call_test_return function. But why does the Call_test_return function stop executing? The reason is that:     exception thrown will stop all code execution "" "#即然有异常 in the Call_test_return function call stack, and it is necessary to deal with it. # try:#     test_return () # except:  #在这里捕捉到了异常, so output the following print statement #      print ("test_return function an exception occurs")   #提示有异常发生 #  print ("End ...") "" "catches the exception and what should be done in case of an exception, therefore, the program is not terminated for the code in the Test_return function that is not executed after the statement that throws the exception is 1, The Try statement can contain any code 2 that might have an exception, and the except statement will catch any type of exception instead of capturing the targeted exception, which is capturing all. 3. How do I capture the specified exception type? Look at the following code "" "#捕捉指定的异常类型def  func_a (number):    try:         return 100 / number    except&nBsp Zerodivisionerror:        print ("can not be 0") #  Print (func_a (0))   #抛出ZeroDivisionError类型的异常 # print (func_a ("abcdef"))   #抛出TypeError类型的异常, but so far the code, No exception was written to capture the TypeError type, so this exception cannot be caught # that is, the TypeError exception is not included in the exception type to be handled # So how can you catch more than one type of exception at the same time? Improved code, as follows Def func_b (number):    try:         return 100 / number    except  (Zerodivisionerror, typeerror):         print ("Unknown value ...") # print (func_b (0)) #  Print (Func_b ("abcdef")) #非常完美, it seems that both types of exceptions are captured # But here's the downside, I want to catch different types of exceptions and do different things for them, the current code is not achievable, #那么, in order to implement this idea, Continue to improve the code as follows Def func_c (number):    try:         return 100 / number    except zerodivisionerror:         print ("Unknown valUE ... ")   #捕获到ZeroDivisionError异常, do this     except TypeError:         print ("Value type error ...")   #捕获到TypeError异常, perform this operation # func_c (0) # func_c ("abc") # print (Func_c) #因此, perfect! #思考一个问题, what happens if you catch any type of exception in front of it? Look at the following code def func_d (number):    try:         return 100 / number    except exception:  #捕获任何异常类型          print ("Exception ....")     except  Zerodivisionerror:        print ("Unknown value ...")      except typeerror:        print ("Value Type  Error ... ") # func_d (0) # func_d (" abc ") #效果是, although it is clear what type of exception will occur and targeted capture, but captures any type of exception at the top, resulting in targeted captures that are not captured at all # Why is that? Because Zerodivisionerror,typeerror these built-in exception types are inherited from the exception class,That is, there is no need for targeted capture. #OK, what would happen if their order was reversed (i.e. except exception in the last)? Look at the following code (the following code removes the capture TypeError type) def func_e (number):    try:         return 100 / number    except  Zerodivisionerror:        print ("Unknown value ...")      except Exception:  #捕获任何异常类型         print ("All  exception) # func_e (0)   #这里引发的是ZeroDivisionError类型的异常 # func_e ("abc")  # This is originally caused by the TypeError type of exception, but it is not able to capture after removal, so the except exception statement is responsible for capturing all the remaining exceptions # through the effect, very perfect, and in what application scenario to use it has not much to say, Obviously know how to apply it "" "did not notice that in the above example, the action after catching an exception is to print a word, but the actual operation is not just to print a word, but also to do other operations, such as doing the operation, or continue to loop, or disconnect, etc. I don't want to just do the operation, I also want to know the specifics of the exception it throws. So how to view? Look at the following code "" "Def func_f (number):    try:         Return 100 / number   &nbsP;except zerodivisionerror as err:        print ("[Error ]:%s [args]:%s " %  (Err, err.args)) # func_f (0) #这里是通过as关键字来捕获到异常作为变量来访问, Err.args is the argument to get to the function of the # keyword as, used in the exception, in the Python3 version, and for Python2, then use a comma "" "said before, the possible exception of the code thrown into the try, So what if the code thrown into the try does not have an exception? If there is no exception, not only do the code in the try, but also I need to do something else, if there is an exception, then only catch the exception, and perform the corresponding action, do not have to perform any additional action. So, look at the following improved code "" "Def func_g (number):    try:         ret =  100 / number        print (ret)     except ZeroDivisionError as err:         print ("[error]:%s [args]:%s"  %  (Err, err.args))     else:         print ("Calculation done ...") # func_g (5)  # Passed in 5 to the function in the calculation, no exception, no exception and also to execute the statement after the else, so that the purpose # func_g (0)   #传入0, the ThrowException, then only the capture operation in except is performed, and the statement after else is not executed "" "The code above seems perfect, and I have another requirement that the statement will perform the actions I specified, regardless of whether an exception occurred," "" Def func_h ( Number):     try:        ret =  100  / number        print (ret)     except  zerodivisionerror as err:        print ("[Error]:%s  [args]:%s " %  (Err, err.args)     else:         print ("Calculation done ...")     finally:         print ("Code end ...") # func_h (0)   #传入0, throws an exception, and continues to execute the finally after statement, But else is not executed, perfect, to my purpose # func_h (8)   #传入的是8, no exception is not required to capture, then else is executed without exception, then he executes. This is very correct, finally the statement also executes the # by seeing the effect, finally really is no matter whether there is an exception occurred, are really going to execute


python--exceptions (built-in exceptions and application scenarios)

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.