Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

Example Analysis of Python exception handling Mechanism

2025-01-18 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)06/02 Report--

This article will explain in detail the example analysis of the exception handling mechanism of Python. The editor thinks it is very practical, so I share it with you as a reference. I hope you can get something after reading this article.

What is an anomaly? Def num (a, b): a = int (a) b = int (b) result = a / b print (result)

The above is a very simple division function, there is no grammatical problem.

But if you call a function, pass in a string. An exception ValueError is thrown. And subsequent code will not be executed

Or, for example, the divisor is 0. That will also throw an exception ZeroDivisionError. And subsequent code will not be executed

Exception handling

Format

Try: # Program code except [errorNmae]: # handling code after an exception [else:] # when there is nothing wrong with the code in try, else is executed. But there can't be retruns in try [finally:] # the code that must be executed in the end is in try-except format-try...except...try: num ('finally,' b') except: print ('your program has a big problem!') Print ('- > end')

Exceptions are handled through try-except, and when an exception is caught, the code in the except section is executed. And the program will not be terminated, continue to execute downward.

Format two-try...except {errorName}...

The above exception handling does not distinguish between exception cases. You can also catch abnormal name for different handling.

Try: num ('averse,' b') except ValueError: print ('your parameter format is not correct!') Except ZeroDivisionError: print ('your divisor is 0') Print ('- > end')

Try: num (10,0) except ValueError: print ('your parameter format is not correct!') Except ZeroDivisionError: print ('your divisor is 0') Print ('- > end')

Format three-try...except {errorName} as key...

Except {errorName} as key . Will assign the error information to key

Note: the error type in Python is also class, and all error types are inherited from BaseException. So when using excpt, you should be aware that if the error type has subtypes, it will also catch all the subtypes.

Try: num (10,0) except ValueError as error_msg_value: print ('your parameter format is incorrect!!' , error_msg_value) except ZeroDivisionError as error_msg_zero: print ('your divisor is 0'. , error_msg_zero) print ('- > end')

This is the case where exceptions are caught using errorName. If the exception is not caught, it will be thrown all the way up and will eventually be thrown by the python interpreter. Print an error message.

Try-except-finally

The final finally executes whether or not an exception is thrown.

Try: num ('averse,' b') except ZeroDivisionError as error_msg_zero: print ('your divisor is zero percent' , error_msg_zero) finally: print ('finally will execute with or without exceptions') print ('- > end')

-

Output:

Your divisor is zero percent! Division by zero

With or without exceptions, finally will execute

-> end

But if the exception has no except and no exception is caught, the exception is finally thrown by the python interpreter. Then after the finally is executed, the subsequent code will not execute.

Try: num ('averse,' b') # except ValueError as error_msg_value:# print ('your parameter format is not correct!!' , error_msg_value) except ZeroDivisionError as error_msg_zero: print ('your divisor is 0'. , error_msg_zero) finally: print ('finally will execute with or without exceptions') print ('- > end')

Try-except-else

When there is nothing wrong with the code in try, else is executed. However, there can be no retrun in try.

Try: num (10,2) except ValueError as error_msg_value: print ('your parameter format is incorrect!!' , error_msg_value) except ZeroDivisionError as error_msg_zero: print ('your divisor is 0'. , error_msg_zero) else: print ('else') finally: print (' finally will execute with or without exceptions') print ('- > end')

-

Output:

5.0

Else

With or without exceptions, finally will execute

-> end

Throw an exception

Format

Raise errorName ('error message')

The error type name can be customized, but try to use the Python built-in error type.

Def num (a, b): result = a / b print (result) if result < 10: raise ValueError ('quotient less than 10, not as expected.') Num (10,2)

Raise can also convert one error type to another

Def ch_type (): try: result = 10 / 0 except ZeroDivisionError as err_msg: raise Exception (err_msg) ch_type ()

The original error type ZeroDivisionError has been changed to Exception.

This is the end of the article on "sample Analysis of Python exception handling Mechanism". I hope the above content can be helpful to you, so that you can learn more knowledge. if you think the article is good, please share it for more people to see.

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report