当前位置:网站首页>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'
边栏推荐
- I What is security testing
- Canoe - the third simulation project - bus simulation - 2 function introduction, network topology
- Strings and characters
- [advantages and disadvantages of outsourcing software development in 2022]
- Software testing related resources
- Understanding of object
- Local MySQL forgot the password modification method (Windows)
- regular expression
- QQ group collection
- 3W word will help you master the C language as soon as you get started - the latest update is up to 5.22
猜你喜欢

2022 AAAI fellow release! Yan Shuicheng, chief scientist of sail, and Feng Yan, Professor of Hong Kong University of science and technology, were selected

Canoe - the second simulation engineering - xvehicle - 2 panel design (operation)

Installation of ES plug-in in Google browser

Canoe test: two ways to create CAPL test module

Fundamentals of software testing

JMeter assembly point technology and logic controller

Appscan installation error: unable to install from Net runtime security policy logout appscan solution
![[Galaxy Kirin V10] [server] KVM create Bridge](/img/a4/a35a276d13e194cefc547607c59f00.jpg)
[Galaxy Kirin V10] [server] KVM create Bridge

Performance test method

Deepmind proposed a Zuan AI, which specially outputs network attack language
随机推荐
Swagger and OpenAPI
本地Mysql忘记密码的修改方法(windows)
re. Sub() usage
20 kinds of hardware engineers must be aware of basic components | the latest update to 8.13
CAPL: on sysVar_ Update difference on sysvar
[Galaxy Kirin V10] [server] grub default password
Terms related to hacker technology
Personal thoughts on the development of game automation protocol testing tool
Heartbeat报错 attempted replay attack
Canoe: what is vtsystem
[Galaxy Kirin V10] [desktop] login system flash back
1. Circular nesting and understanding of lists
Hidden C2 tunnel -- use of icmpsh of ICMP
TS type gymnastics: illustrating a complex advanced type
Customized version of cacti host template
[Galaxy Kirin V10] [server] FTP introduction and common scenario construction
Simple understanding of string
Interview and lecture summary 1
Usage of case when then else end statement
Simple understanding of generics