Basic Python-Exception Handling and basic python exception handling

Source: Internet
Author: User

Basic Python-Exception Handling and basic python exception handling

1. What is an exception?

An exception is an event that occurs during program execution and affects normal execution of the program. Generally, an exception occurs when Python cannot process the program normally.

An exception is a Python object, indicating an error. When a Python script exception occurs, we need to capture and process it; otherwise, the program will terminate the execution.

Different exceptions in python can be identified by different types (classes and types are unified in python, and classes are called classes). Different class objects have different identifiers, an exception indicates an error:

Exception name Description
BaseException All abnormal base classes
SystemExit Interpreter request to exit
KeyboardInterrupt User interrupted execution (usually input ^ C)
Exception Base class with regular errors
StopIteration The iterator does not have more values.
GeneratorExit Generator exception to notify exit
StandardError All base classes with built-in standard exceptions
ArithmeticError Base classes with incorrect numeric calculation
FloatingPointError Floating Point Calculation Error
OverflowError The value operation exceeds the maximum limit.
ZeroDivisionError Except (or modulo) zero (all data types)
AssertionError Assertion statement failed
AttributeError The object does not have this property.
EOFError No built-in input, reaching the EOF tag
EnvironmentError Operating System Error base class
IOError Input/Output operation failed
OSError Operating System Error
WindowsError System Call failed
ImportError Import module/object failed
LookupError Base class for invalid data query
IndexError This index is not found in the sequence)
KeyError The ing does not contain this key.
MemoryError Memory overflow error (not fatal for Python Interpreter)
NameError Object not declared/initialized (no attribute)
UnboundLocalError Access uninitialized local variables
ReferenceError Weak reference attempts to access garbage collection objects
RuntimeError General running errors
NotImplementedError Unimplemented Methods
SyntaxError Python syntax error
IndentationError Indentation Error
TabError Mix Tab and Space
SystemError General interpreter system error
TypeError Operation that is invalid for the Type
ValueError Invalid parameter passed in
UnicodeError Unicode errors
UnicodeDecodeError Unicode decoding error
UnicodeEncodeError Unicode Encoding Error
UnicodeTranslateError Unicode Conversion error
Warning Warning base class
DeprecationWarning Warning about discarded features
FutureWarning Warning about future semantic changes in Construction
OverflowWarning Old warning about automatic upgrade to long (long)
PendingDeprecationWarning Warning that features will be discarded
RuntimeWarning Warning of suspicious running behavior (runtime behavior)
SyntaxWarning Warning of suspicious syntax
UserWarning Warning generated by user code

Ii. Exception Handling

1. What is exception handling?

  • The python interpreter detects an error and triggers an exception (it also allows programmers to trigger the exception themselves)
  • Programmers write specific code specifically to catch this exception (this code is irrelevant to the Program Logic and related to Exception Handling)
  • If the capture succeeds, it will go to another Processing Branch and execute the logic you have customized for it so that the program will not crash. This is exception handling.

2. Why handle exceptions?

The python parser executes the program. When an error is detected, it triggers an exception. When an exception is triggered and not processed, the program terminates at the current exception, the code below will not run, and who will use a software that suddenly crashes. Therefore, you must provide an exception processing mechanism to enhance the robustness and fault tolerance of your program.

3. How to handle exceptions

Note: exceptions are caused by program errors. syntax errors are irrelevant to Exception Handling and must be corrected before running the program.

A. Use if

1 # _ * _ coding: UTF-8 _ * _ 2 _ author _ = 'linhaifeng '3 4 # code 5 num1 = input (' >> :') # enter a string and try 6 int (num1) 7 8 9 # code 10 num2 = input ('>>:') # enter a string and try 11 int (num2) 12 13 # Code 14 num3 = input ('>>:') # enter a string and try 15 int (num3)
Normal code

 

1 # _ * _ coding: UTF-8 _ * _ 2 _ author _ = 'linhaifeng '3 4 num1 = input (' >> :') # enter a string and try 5 if num1.isdigit (): 6 int (num1) # Here we put our Orthodox program, and the rest belong to the exception handling category 7 elif num1.isspace (): 8 print ('enter a space and execute the logic here ') 9 elif len (num1) = 0: 10 print ('enter blank, execute the logic here. ') 11 else: 12 print ('other situations, execute the logic here ') 13 14 # code 15 # num2 = input ('>:') # enter a string and try 16 # int (num2) 17 18 # Code 19 # num3 = input ('>:') # enter a string and try 20 # int (num3) 21 22 ''' 23 problem 1: 24 when using the if method, we only add exception handling to the first code. For the second code, you have to re-write a bunch of if, elif and so on, you have to write it again. Of course, you said, it can be combined. That's right. Let's take a look at it together, can your code be understood ??? 26. These if statements have nothing to do with your code logic. This is like pulling them everywhere in your beloved program and pulling them to the end. No one cares about your bad code. Why, because of the poor readability, I cannot understand 27 28 problem 2: 29 the first and second sections of code are actually the same exception, both of which are ValueError. the same errors can be handled only once, if, because the two if conditions are different, it only forces you to re-write a new if to handle the exception of the second code. The third section is also the same as 31 '''
Exception Handling using if judgment

Summary:

  • If primitive exception handling can only be performed on a specific piece of code. For errors of the same type in different code segments, you need to write duplicate if statements for processing.
  • Frequent write in your program is irrelevant to the program itself, and if related to exception handling is like pulling around in your code. Extremely poor readability
  • This can solve the exception, but there are 1 and 2 problems. Therefore, do not draw a conclusion that if cannot be used for exception handling. If you don't accept it, do you think your program has no exception handling before learning try... crash T, and let it crash?

B. try/try t

  • Syntax:
1 try: 2 detected code block 3 handle T exception type: 4 try once an exception is detected, execute the logic at this location
  • It can only be used to handle specified exceptions. If it is not specified, it cannot be handled:
1 # If no exception is caught, the program directly reports an error 2 3 s1 = 'hello' 4 try: 5 int (s1) 6 failed t IndexError as e: 7 print e

 

  • Multiple branches:
1 # Form 1 2 3 s1 = 'hello' 4 try: 5 int (s1) 6 handle T IndexError as e: 7 print (e) 8 handle T KeyError as e: 9 print (e) 10 records t ValueError as e: 11 print (e) 12 13 14 15 # form 216 17 try: 18 normal operations 19 ...................... 20 t (prediction1 [, prediction2 [,... exceptionN]): 21. One of the above exceptions occurs, execute this code 22 ......................
  • Universal exception
1 s1 = 'hello' 2 try: 3 int (s1) 4 random t Exception as e: # Exception, can catch any Exception 5 print (e)

 

If whatever exceptions occur, we discard them in a unified manner, or use the same code logic to process them, then only one Exception is enough.

If we need to customize different processing logic for different exceptions, we need to use multiple branches. We can also create an Exception after multiple branches:

 1 s1 = 'hello' 2 try: 3     int(s1) 4 except IndexError as e: 5     print(e) 6 except KeyError as e: 7     print(e) 8 except ValueError as e: 9     print(e)10 except Exception as e:11     print(e)
  • Other abnormal structures: try/retry t/else/finally
1 s1 = 'hello' 2 try: 3 int (s1) 4 handle T IndexError as e: 5 print (e) 6 handle T KeyError as e: 7 print (e) 8 bytes t ValueError as e: 9 print (e) 10 # bytes t Exception as e: 11 # print (e) 12 else: 13 print ('execute me if there is no exception in the try code block ') 14 finally: 15 print ('execute this module regardless of the exception or not, usually for cleanup ')

 

  • Actively trigger exceptions
1 # _ * _ coding: UTF-8 _ * _ 2 _ author _ = 'linhaifeng' 3 4 try: 5 raise TypeError ('Type error') 6 precondition t Exception as e: 7 print (e)
  • Custom exception
1 # _ * _ coding: UTF-8 _ * _ 2 _ author _ = 'linhaifeng' 3 4 class EgonException (BaseException): 5 def _ init _ (self, msg): 6 self. msg = msg 7 def _ str _ (self): 8 return self. msg 9 10 try: 11 raise EgonException ('Type error') 12 failed t EgonException as e: 13 print (e)
  • Assert
1 # assert condition 2 3 assert 1 = 14 5 assert 1 = 2
  • Try/try t to compare the advantages of if

Try/try t. This exception handling mechanism replaces the if method, so that your program can enhance robustness and fault tolerance without sacrificing readability.

The exception type is customized for each exception in exception handling (classes and types are unified in python, and classes are called classes). For the same exception, an exception t can be captured, multi-segment code exceptions can be processed simultaneously (without the need to 'write multiple if else type') to reduce code and enhance readability:

1 # _ * _ coding: UTF-8 _ * _ 2 _ author _ = 'linhaifeng '3 4 # num1 = input (' >> :') # enter a string and try 5 # if num1.isdigit (): 6 # int (num1) # Our orthodox program is here, and the rest belong to the exception handling category 7 # elif num1.isspace (): 8 # print ('enter space and execute the logic here. ') 9 # elif len (num1) = 0: 10 # print ('enter blank, execute the logic here. ') 11 # else: 12 # print ('other situations, execute the logic here ') 13 14 # code 15 # num2 = input ('>:') # enter a string and try 16 # int (num2) 17 18 # Code 19 # num3 = input ('>:') # enter a string and try 20 # int (num3) 21 22 try: 23 # code 24 num1 = input ('>:') # enter a string and try 25 int (num1) # Here is our Orthodox program, the rest belong to the exception handling scope 26 # The second code 27 num2 = input ('>>:') # enter a string and try 28 int (num2) 29 # code 30 num3 = input ('>>:') # enter a string and try 31 int (num3) 32 characters t ValueError as e: 33 print (e)

Advantages of using try... try t:

Iii. When to handle exceptions

Try/try t should be used as little as possible, because it is an exception handling logic that you attach to your program. It has nothing to do with your main work, this kind of stuff is added more, which will cause your code to become less readable.

Try... retry T should be added only when some exceptions are unpredictable, and other logical errors should be corrected as much as possible.

 

 

References:

1. http://www.cnblogs.com/linhaifeng/articles/6232220.html

2. http://www.runoob.com/python/python-exceptions.html

 

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.