Preface
One 、 abnormal
1.1、 Ignore
1.2、 Capture
1.3、 Abnormal chain
1.4、 Customize
1.5、 Throw out
Two 、 Abnormal display mode
2.1、 Print information
2.2、 Console warning
2.2、 Storage file
Prefacecomparison java,python Exceptions and java Different from ,python It mainly prevents program exceptions from being aborted . Once being catch After that, it can be executed further .
One 、 abnormal 1.1、 Ignorepass This keyword is equivalent to a placeholder , like TODO It's the same , It just means that I will do nothing on this trip , It does not mean that other lines of code will not be executed ;
try:print(5/0)except ZeroDivisionError:passprint("ddd") # This line can still be executed normally
1.2、 Capture def parse_int(s):try:n = int(v)except Exception as e:print('Could not parse, Reason:', e)parse_int('30') ##Reason: name 'v' is not defined
1.3、 Abnormal chain try:client_obj.get_url(url)except (URLError, ValueError, SocketTimeout):client_obj.remove_url(url)
try:client_obj.get_url(url)except (URLError, ValueError):client_obj.remove_url(url)except SocketTimeout:client_obj.handle_url_timeout(url)
try:f = open(filename)except OSError:pass
1.4、 Customize class NetworkError(Exception):passclass HostnameError(NetworkError):passclass CustomError(Exception):def __init__(self, message, status):super().__init__(message, status)self.message = messageself.status = status
try:msg = s.recv()except TimeoutError as e:print(e)except RuntimeError as e:print(e.args)
1.5、 Throw out try:raise RuntimeError('It failed') # Throw a new exception -raise Errorexcept RuntimeError as e:print(e.args)
def example():try:int('N/A')except ValueError:print("Didn't work")raise # Throw after capture
Two 、 Abnormal display mode 2.1、 Print information try:print(5/0)except ZeroDivisionError as e:print(e.args)
2.2、 Console warning import warningswarnings.simplefilter('always')def func(x, y, log_file=None, debug=False):if log_file is not None:warnings.warn('log_file argument deprecated', DeprecationWarning)func(1, 2, 'a')# Output the first line of the log warn Content , The second line outputs the contents of the code /Users/liudong/personCode/python/pythonTest/app/base/base_type.py:5: UserWarning: log_file argument deprecatedwarnings.warn('log_file argument deprecated')
2.2、 Storage file import json;numbers = [2,3,4,5,6];fileName = "numbers.json";with open(fileName, "w") as fileObj:json.dump(numbers, fileObj);with open(fileName, "r") as fileObj:number1 = json.load(fileObj);
This is about Python This is the end of the article on packaging exception handling methods , More about Python Please search the previous articles of SDN or continue to browse the related articles below. I hope you will support SDN more in the future !