当前位置:网站首页>Exceptions and exception handling
Exceptions and exception handling
2022-07-04 11:08:00 【It's a cinch!】
abnormal :
Compared with normal, abnormal phenomena are called anomalies , Encountered errors or BUG All are
Supplement normal conditions ( Errors are not exceptions , Exceptions are not equivalent to errors , Exception refers to the software running , For some reason ( Improper use by users ) Program error caused by , The phenomenon that leads to software crash is called exception )
Abnormal consequences : Cause the program to crash
Handling exceptions :
There are abnormal errors in tolerance , Ensure the normal operation of the program
Processing mode :try : - except: Sentence block Exception trapping
Code exception : It does not affect the execution of the following code , You need to continue to execute the following code
Format :
try:
# Code where exceptions can occur
except:
# Handling exceptions
Custom exception :
finally keyword : Code that must be executed ( Release resources 、io)
If in a function , If return Post existence finally keyword , Then the code will not
Go straight back to ( perform return), But to perform finally Code block , Then execute the return (return), all finally Will be in return Before execution
Common abnormal :
import builtins
dir(builtins)
Abnormal inheritance relationship :
BaseException() The parent of all exceptions
Exception() (BaseException() Subclasses of ) Is the parent of common exceptions
Custom exception :
First create a class , Inherit Exception perhaps BaseException, It is recommended to use Exception class
class MyException(Exception):
def __init__(self):
Exception.__init__(self,msg)
def login(username,password):
if username==None or username.strip()=='':
# Throw an exception —— Use raise keyword ( Custom throw exception )
raise MyException(" The username cannot be empty ")
if password==None or password.strip()=='':
# Throw an exception —— Use raise keyword ( Custom throw exception )
raise MyException(" The password cannot be empty ")
if __name__ == '__main__':
try:
#login(None,None)
# Capture exception
login(None,None)
except Exception as e:
print(" Exception caught as >>>>",e)
'ArithmeticError', 'AssertionError', 'AttributeError', 'BaseException', 'BlockingIOError', 'BrokenPipeError', 'Buffer
Error', 'BytesWarning', 'ChildProcessError', 'ConnectionAbortedError', 'ConnectionError', 'ConnectionRefusedError', 'C
onnectionResetError', 'DeprecationWarning', 'EOFError', 'Ellipsis', 'EnvironmentError', 'Exception', 'False', 'FileExi
stsError', 'FileNotFoundError', 'FloatingPointError', 'FutureWarning', 'GeneratorExit', 'IOError', 'ImportError', 'Imp
ortWarning', 'IndentationError', 'IndexError', 'InterruptedError', 'IsADirectoryError', 'KeyError', 'KeyboardInterrupt
', 'LookupError', 'MemoryError', 'ModuleNotFoundError', 'NameError', 'None', 'NotADirectoryError', 'NotImplemented', '
NotImplementedError', 'OSError', 'OverflowError', 'PendingDeprecationWarning', 'PermissionError', 'ProcessLookupError'
, 'RecursionError', 'ReferenceError', 'ResourceWarning', 'RuntimeError', 'RuntimeWarning', 'StopAsyncIteration', 'Stop
Iteration', 'SyntaxError', 'SyntaxWarning', 'SystemError', 'SystemExit', 'TabError', 'TimeoutError', 'True', 'TypeErro
r', 'UnboundLocalError', 'UnicodeDecodeError', 'UnicodeEncodeError', 'UnicodeError', 'UnicodeTranslateError', 'Unicode
Warning', 'UserWarning', 'ValueError', 'Warning', 'WindowsError', 'ZeroDivisionError', '__build_class__', '__debug__',
'__doc__', '__import__', '__loader__', '__name__', '__package__', '__spec__', 'abs', 'all', 'any', 'ascii', 'bin', 'b
ool', 'breakpoint', 'bytearray', 'bytes', 'callable', 'chr', 'classmethod', 'compile', 'complex', 'copyright', 'credit
s', 'delattr', 'dict', 'dir', 'divmod', 'enumerate', 'eval', 'exec', 'exit', 'filter', 'float', 'format', 'frozenset',
'getattr', 'globals', 'hasattr', 'hash', 'help', 'hex', 'id', 'input', 'int', 'isinstance', 'issubclass', 'iter', 'le
n', 'license', 'list', 'locals', 'map', 'max', 'memoryview', 'min', 'next', 'object', 'oct', 'open', 'ord', 'pow', 'pr
int', 'property', 'quit', 'range', 'repr', 'reversed', 'round', 'set', 'setattr', 'slice', 'sorted', 'staticmethod', '
str', 'sum', 'super', 'tuple', 'type', 'vars', 'zip'
边栏推荐
- Canoe test: two ways to create CAPL test module
- Canoe-the second simulation project-xvehicle-1 bus database design (idea)
- For and while loops
- Postman advanced
- Canoe - description of common database attributes
- Canoe - the third simulation project - bus simulation - 2 function introduction, network topology
- QQ get group information
- Performance features focus & JMeter & LoadRunner advantages and disadvantages
- Safety testing aspects
- Test question bank management system - database design [easy to understand]
猜你喜欢
[Galaxy Kirin V10] [server] set time synchronization of intranet server
Oracle11g | getting started with database. It's enough to read this 10000 word analysis
QQ group administrators
Postman interface test
Canoe: what is vtsystem
Automatic translation between Chinese and English
Using Lua to realize 99 multiplication table
JMeter common configuration components and parameterization
Write a thread pool by hand, and take you to learn the implementation principle of ThreadPoolExecutor thread pool
Personal thoughts on the development of game automation protocol testing tool
随机推荐
[Galaxy Kirin V10] [server] failed to start the network
Canoe: what is vtsystem
No response after heartbeat startup
QQ get group member operation time
Aike AI frontier promotion (2.14)
MBG combat zero basis
Notes on writing test points in mind mapping
Using SA token to solve websocket handshake authentication
本地Mysql忘记密码的修改方法(windows)[通俗易懂]
2、 Operators and branches
What if the book written is too popular? Author of "deep reinforcement learning" at Peking University: then open the download
thread
Dictionaries and collections
Terms related to hacker technology
Send a request using paste raw text
Usage of case when then else end statement
Using Lua to realize 99 multiplication table
Oracle11g | getting started with database. It's enough to read this 10000 word analysis
3W word will help you master the C language as soon as you get started - the latest update is up to 5.22
QQ get group information