python provides exception handling try....except in the following format
- try:
- print("Logical processing code block")
- except Exception as e:
- print("Code block execution error exception", e)
- else:
- print("Logical code block execution no error execute this part")
- finally:
- print("Code block part that executes with or without errors")
As shown above, python calls the Exception class when it catches the Exception. This is an Exception base class, and e is an Exception object similar to
e = Exception()
But we know that the instantiated e should be an object. If print(e) is executed, it should be a memory address. For example:
- class A():
- pass
- a = A()
- print(a)
- Result:
- <__main__.A object at 0x00000000031ACE48>
So why did we return an error message when we called print(e).
Let's look at the following example:
- class A():
- def __init__(self):
- pass
- def __str__(self):
- return "class A str function"
- a = A()
- print(a)
- Result:
- class A str function
Yes, after adding a str function to the class, when print(a) is no longer the memory address, it automatically calls the str function. So print(e) also calls the Exception's STR function.
raise anomaly
In the process of executing code with try...exception statement, the system will return error information to variable e after exception. See the following example:
- a = 1
- b = 2
- try:
- c = a + b
- if c == 4:
- print(c)
- else:
- raise Exception("Error")
- except Exception as e:
- print(e)
- Result:
- Error
Yes, we can return the error information to e through the exception class through raise, so that we can output our customized error information. Is it convenient to see. In this case, we can customize a class
Custom exception
Here's an example:
- class MyException(Exception):
- CODE1 = "10000" #Wrong user name and password
- CODE2 = "10001" #User does not exist
- def __init__(self, error_msg):
- self._msg = error_msg
- def __str__(self):
- if self._msg == "10000":
- return "Wrong user name and password"
- if self._msg == "10001":
- return "user does not exist"
- if __name__ == "__main__":
- user = input("User name:")
- pwd = input("Password:")
- try:
- if user == "peter":
- if pwd == "12345":
- print("Login successfully")
- else:
- raise MyException("10000")
- else:
- raise MyException("10001")
- except MyException as e:
- print(e)