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

How to deal with errors and exceptions in Python

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

Share

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

This article mainly introduces how to deal with errors and exceptions in Python, which has a certain reference value. Interested friends can refer to it. I hope you will gain a lot after reading this article.

Preface

Grammatical error

The SyntaxError class represents a syntax error that is triggered when the interpreter finds that the code fails the syntax check. Syntax error is that try...except... cannot be used Captured.

> print: File "", line 1 print: ^ SyntaxError: invalid syntax exception

Python uses a special object called an exception to manage errors that occur during program execution. Whenever an error occurs that overwhelms Python, it creates an exception object, and if you write code to handle the exception, the program continues to run; if the exception is not handled, the program stops and displays a traceback with a report on the exception.

Exception handling print (5thumb 0)

Running result:

Traceback (most recent call last): File "Files and exceptions / Files and exceptions. Py", line 228, in print (5max 0) ZeroDivisionError: division by zero

Exception handling uses the following format:

Try-except code block

Try-except code block try: print (5Accord 0) except ZeroDivisionError: print ("can't divide by zero") # result print ("can't divide by zero") throws an exception

Use the raise statement to throw a specified exception.

The only parameter to raise specifies the exception to be thrown. It must be an instance of an exception or an exception class (that is, a subclass of Exception).

If you just want to know if an exception is thrown and don't want to handle it, a simple raise statement can throw it again.

Custom exception

You can have your own exceptions by creating a new exception class. Exception classes inherit from the Exception class and can be inherited directly or indirectly.

When creating a module has the potential to throw many different exceptions, a common practice is to create a base exception class for the package, and then create different subclasses for different error situations based on this base class.

Most exception names end with "Error", just like standard exception names.

Example

Import sysclass Error (Exception): "Base class for exceptions in this module." Pass# custom exception class InputError (Error): "Exception raised for errors in the input. Attributes: expression-- input expression in which the error occurred message-- explanation of the error" def _ init__ (self, expression, message): self.expression = expression self.message = messagetry: print ('code start running...') " Raise InputError ('input (),' input error') # ValueError int ('a') # TypeError s = 1 +'a' dit = {'name':' john'} # KeyError print (dit ['1']) except InputError as ex: print ("InputError:", ex.message) except TypeError as ex: print ('TypeError:', ex.args) passexcept (KeyError, IndexError) as ex: "" supports simultaneous handling of multiple exceptions Put parentheses in the tuple "print (sys.exc_info ()) except:" catch other unspecified exceptions "print (" Unexpected error: ", sys.exc_info () [0]) # raise is used to throw an exception raise RuntimeError ('RuntimeError') else:" when there are no exceptions Will execute the else clause "print" ('"else" clause...') finally: "regardless of whether there is an exception or not, finally will be executed"print ('finally, ending') Thank you for reading this article carefully. I hope the article "how to deal with errors and anomalies in Python" shared by the editor will be helpful to you. At the same time, I also hope that you will support us and pay attention to the industry information channel. More related knowledge is waiting for you to learn!

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

Internet Technology

Wechat

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

12
Report