当前位置:网站首页>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'
边栏推荐
- No response after heartbeat startup
- Jemeter plug-in technology
- JMeter assembly point technology and logic controller
- Article publishing experiment
- Using SA token to solve websocket handshake authentication
- Jemeter script recording
- LVS+Keepalived实现四层负载及高可用
- Solaris 10网络服务
- Open the neural network "black box"! Unveil the mystery of machine learning system with natural language
- 试题库管理系统–数据库设计[通俗易懂]
猜你喜欢

Canoe - the third simulation project - bus simulation-1 overview

Ten key performance indicators of software applications

Automatic translation between Chinese and English

QQ group collection
![[machine] [server] Taishan 200](/img/e5/69a1a4ca04814a033a77d3cb4601b3.jpg)
[machine] [server] Taishan 200

Discussion | has large AI become autonomous? Lecun, chief scientist of openai

F12 clear the cookies of the corresponding web address

Notes on writing test points in mind mapping

Elevator dispatching (pairing project) ③

OSI model notes
随机推荐
If function in SQL
[Galaxy Kirin V10] [server] system startup failed
Test question bank management system - database design [easy to understand]
Deepmind proposed a Zuan AI, which specially outputs network attack language
[Galaxy Kirin V10] [server] iSCSI deployment
Heartbeat启动后无反应
Using Lua to realize 99 multiplication table
QQ get group member operation time
[Galaxy Kirin V10] [desktop] can't be started or the screen is black
First article
Capl: timer event
Application and Optimization Practice of redis in vivo push platform
Replace() function
1. Circular nesting and understanding of lists
Canoe: the difference between environment variables and system variables
Iterator generators and modules
Usage of with as
Swagger and OpenAPI
2021-11-02
Write a thread pool by hand, and take you to learn the implementation principle of ThreadPoolExecutor thread pool