Exception handling for Python beginners

Keywords: Python

1. Exception handling

(1) there are two kinds of errors in the program

< 1 > syntax error

(this kind of error can't pass the syntax detection of Python interpreter at all. It must be corrected before the program is executed.)

# Syntax error demonstration
    print(111
    [1;2;3;4]
< 2 > logic error
# Example of logical error
    lst = [1,2,3]
    lst[5]

    dic = {"key":1}
    dic["name"]

    1 + "alex"
    int("alex")

    name = "alex"
    def func():
        print(name)
        name = "a"
    func()

(2) what is abnormality?

Exception is a signal of an error when the program is running. Removing the syntax error is an exception.

(exception means that there is no problem in syntax, but it is called exception when an error is reported at runtime. After the exception occurs, the remaining code will not continue to execute.)

(3) type of abnormality:

Different exceptions in Python can be identified by different types (Python unifies class and type, type is class), different class objects identify different exceptions, an exception identifies an error

Common exceptions:
Exception type Exception description
AttributeError An attempt was made to access a property that an object does not have, such as f.x, but f does not have property x
ImportError Unable to import module or package; basically path or name error
IndentationError Code not aligned correctly
IndexError Subscript index out of sequence index boundary
KeyError An attempt was made to access a key that does not exist in the dictionary
NameError Use a variable that has not been assigned to an object
SyntaxError Python encountered illegal code, code cannot be compiled
TypeError The incoming object type does not meet the requirements
UnboundLocalError The attempt to access a local variable that has not been set is basically due to another global variable with the same name
ValueError Pass in a value that the caller does not expect, even if the value type is correct

More exceptions:

ArithmeticError
AssertionError
AttributeError
BaseException
BufferError
BytesWarning
DeprecationWarning
EnvironmentError
EOFError
Exception
FloatingPointError
FutureWarning
GeneratorExit
ImportError
ImportWarning
IndentationError
IndexError
IOError
KeyboardInterrupt
KeyError
LookupError
MemoryError
NameError
NotImplementedError
OSError
OverflowError
PendingDeprecationWarning
ReferenceError
RuntimeError
RuntimeWarning
StandardError
StopIteration
SyntaxError
SyntaxWarning
SystemError
SystemExit
TabError
TypeError
UnboundLocalError
UnicodeDecodeError
UnicodeEncodeError
UnicodeError
UnicodeTranslateError
UnicodeWarning
UserWarning
ValueError
Warning
ZeroDivisionError

(4) exception handling:

"Skip" exceptions and codes under exceptions after detecting exceptions to ensure that the program will not be interrupted

Exception handling method:

< 1 > If exception handling -- if handling some simple exceptions
num = input(">>")
if num.isdecimal():
    int(num)
if len(num) == 0:
    pass

    # If handling some simple exceptions, if handling methods

Conclusion:

If judgmental exception handling can only be used for a certain piece of code. For the same type of errors in different code sections, you need to write duplicate if to handle them.

Frequent writing in your program has nothing to do with the program itself. if related to exception handling will make your code extremely poor readability.

If can solve exceptions, but there are 1 and 2 problems. Therefore, do not jump to the conclusion that if cannot be used for exception handling.

< 2 > try method -- private customization
try:        # attempt
    int("alex")
except ValueError:
    """Other code logic"""
try:

    [1,2,3][7]
    print(111)
    dic = {"key":1}
    dic["name"]
except Exception:         # Universal Exception -- Exception, which can catch any Exception
    pass

(5) why use exception handling?

< 1 > if there is an exception, the code under the exception will not execute (interrupt).

< 2 > bad user experience

(6) abnormal branch

< 1 > execute different logic according to different branches

try:
    int(input("please enter a number:"))

except ValueError as e:       # as is equivalent to assigning error information to e
    print(e)


try:
    int(input("please enter a number:"))

except Exception as e:
    print(e)

int(input("please enter a number:"))

< 2 > branch + omnipotent + else + finally

try:
    num = int(input("please enter a number:"))
    lst = [1,2,3]
    # dic = {"name":"mee",1:"imo"}
    # print(dic[num])
    print(lst[num])

except ValueError as e:
    print(e)

except KeyError as e:
    print(f"No,{e}This key")

except IndexError as e:
    print(e)

except Exception as e:
    print(e)

else:
    print("No mistake.,Walk me!")

finally:
    print("Is there a mistake?,Leave me.!,Clean-up work")

< 3 > try....... Except

class EvaException(BaseException):
    def __init__(self,msg):
        self.msg = msg
    def __str__(self):
        return self.msg

try:
    a = EvaException('error in type')
    raise a
except EvaException as e:
    print(e)

< 4 > use try..except to summarize:

Separate error handling from real work

The code is easier to organize, clearer, and the complex tasks are easier to implement. 

There's no doubt that it's safer, and it won't cause the program to crash accidentally due to some minor negligence;

(7) when to use exception handling?

try...except should be used as little as possible, because it is an exception handling logic attached to your program. It has nothing to do with your main work. Adding more of this kind of thing will lead to poor readability of your code. Only when some exceptions are unpredictable, try...except should be added. Other logic errors should be corrected as much as possible.

2, assertion

assert condition

assert 1 == 1

if 1 == 1:
    print(111)

assert 1 == 2
if 1 == 2:
    print(222)

Posted by php-coder on Wed, 23 Oct 2019 23:52:51 -0700