python exception handling

Keywords: Python

1. Exception handling

The difference between Error and Exception:

Error is a system error that programmers cannot change or handle, such as a system crash, insufficient memory, method call stack overflow, etc. In the event of such an error, it is recommended that the program be terminated.

Exception indicates an exception that the program can handle, which can be caught and possibly recovered. When such exceptions are encountered, they should be handled as far as possible so that the program can resume running and not terminate at will.

Common errors are:

print(a)   # NameError
print(10/0)# ZeroDivisionError: division by zero
d = {'name':'test'}
print(d['obj'])  #KeyError: 'obj'
with open('hello.txt') as f:
    pass  #FileNotFoundError: [Errno 2] No such file or directory: 'hello.txt'
a=b=18
if a>b:
    print('error')
  else:
    print('Correct')
    #IndentationError: unindent does not match any outer indentation level

Common Exceptions

AttributeError ,IOError ,ImportError ,IndexError, SyntaxError,TypeError,ValueError,KeyError,NameError
IndentationError: Indentation error
KeyboardInterrupt: Ctrl+C is pressed
UnboundLocalError: A global variable with the same name

Exception handling mechanism

Common exception mechanisms are:
try, except, else, finally, and raise.
Describe each:

The indented code block after the try keyword is referred to as the try block. It contains code that may cause an exception.
The except keyword corresponds to the exception type and the block of code that handles the exception. An else block can be placed after several except blocks, indicating that an else block should be executed when no exception occurs in the program.
The final block is used to recycle physical resources opened in the try block, and the exception mechanism guarantees that the final block will always be executed.
Raise is used to raise an actual exception, which can be used as a statement alone to raise a specific exception object.

To summarize, this is:
else:What to execute if there are no exceptions
finally: what will always be executed

try:
    a = 1
    print(b)
except NameError as e:
    print('name error')
except KeyError:
    print('key error')
except Exception as e:
    print('exception')
else:
    print('no error')
finally:
    print('always run')

The result of execution is

name error
always run

Common abnormal uses

An exception is an error, is it all bad?
Exceptions also have many benefits, and a common use in standard Python libraries is to try to import a module and check if it can be used. Importing a module that does not exist raises an ImportError exception. That way we can try out the module and find the most effective way to use it

Trigger of anomaly detection

In fact, python allows spontaneous exception testing, and self-exception testing is done with a raise statement
Exception in a raise statement is either of the type of exception (for example, NameError) parameter standard exceptions, and args is the exception parameter provided by itself.

raise [Exception [, args [, traceback]]]
age = int(input('age:'))
if 0<age<100:
    print(age)
else:
    raise ValueError("Age must be 0~100 Between")

The result of the code is:

age:101
Traceback (most recent call last):
  File "C:\Users\12261\Desktop\Study\python\day_06\1.py", line 5, in <module>
    raise ValueError("Age must be 0~100 Between")
ValueError: Age must be 0~100 Between

Custom Exception

Custom exceptions should inherit either the Exception base class or a subclass of Exception.
In the customization process, simply specify the parent class of the custom exception class.

class AgeError(ValueError):
    pass

age = int(input('age:'))
if 0<age<100:
    print(age)
else:
    raise AgeError("Age must be 0~100 Between")

The results are as follows:

age:202
Traceback (most recent call last):
  File "C:\Users\12261\Desktop\Study\python\day_06\1.py", line 8, in <module>
    raise AgeError("Age must be 0~100 Between")
__main__.AgeError: Age must be 0~100 Between

Cautions for unusual use

You can't use too many exceptions
Do not enter too many decisions in the try module
Don't forget the exception that pops up while testing

Posted by rofl90 on Sun, 28 Nov 2021 11:24:00 -0800