Example: When opening a non-existent file:
>>open("abc.txt","r")
Will prompt errorsTraceback (most recent call last):
File "D:/project1/test.py", line 11, in <module>
open("abc.txt","r")
FileNotFoundError: [Errno 2] No such file or directory: 'abc.txt'
This exception can then be caught and handled with try....except statement
try: open("abc.txt","r") except FileNotFoundError: print("Error")
----------------------
At this point, the operation will only print "Error"
If the statement is replaced by:
try: print(a) except FileNotFoundError: print("Error")
----------------------Traceback (most recent call last):
File "D:/project1/test.py", line 12, in <module>
print(a)
NameError: name 'a' is not defined
At this time, because "FileNotFoundError" means an error when a file cannot be found, which is not consistent with the current "NameError", the code can be changed to the following:
try: print(a) except NameError: print("Error")
However, in Python, all exceptions are inherited from Exception. Since version 2.5, a new base class BaseException has emerged, and the new base class can accept all exceptions:
try: print(a) open("abc.txt","r") except BaseException: print("Error")
-------------------------
No matter which line is abnormal, we can catch and print "Error" but we can't know which line is wrong. At this time, we can print the abnormal information:try: print(a) open("abc.txt","r") except BaseException as msg:
print(msg) print("Error")
-------------------------
[Errno 2] No such file or directory: 'abc.txt'
The following are common exceptions in Python:
BaseException | The base class of all new exception classes |
Exception | All exceptional base classes, but inherited from BaseException |
AssertionError | asser statement failed |
FileNotFoundError | Attempt to open a file or directory that does not exist |
AttributeError | The object you are trying to access has no properties |
OSError | This exception is raised when the system function returns a system-related error (including an I/O failure), such as "File not found" or "Disk is full" |
NameError | Use a variable of an unassigned object |
IndexError | Raise this exception when a sequence goes out of range |
SyntaxError | Raises this exception when the parser encounters a syntax error |
KeyboardInterrupt | The combination key Ctrl+C is pressed and the program is forced to terminate |
TypeError | Incoming object types do not match requirements |
The use of exceptions combined with else:
try: a ="Exception testing:" print(a) except NameError as msg: print(msg) esle: print("Execution without exception")
------------------------------
Print exception information when an exception occurs“ msg",When there are no exceptions, execute esle,Print "Execute without exception"
The use of an exception in conjunction with finallyd:
try: print(a) except NameError as msg: print(msg) finally: print("Execution regardless of exceptions finally)
User-defined exception throws raise:
class loogExcept(Exception): def __init__(self,leng): self.leng = leng def __str__(self): print("Your Name:"+str(self.leng)+",Over the length!") def name_Test(): try: name = input("enter your name:") if len(name) > 4: raise loogExcept(len(name)) else: print(name) except loogExcept as e_result: print("Anomalies caught") print("Print exception:",e_result) if __name__ == "__main__": name_Test()
---------------------------------------------enter your name:sadsadasd
Anomalies caught
Print exception: your name: 9,Over the length!
Your name: 9,Over the length!
Traceback (most recent call last):
File "D:/project1/test.py", line 19, in name_Test
raise loogExcept(len(name))
__main__.loogExcept: <exception str() failed>During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "D:/project1/test.py", line 27, in <module>
name_Test()
File "D:/project1/test.py", line 24, in name_Test
print("Print exception:",e_result)
TypeError: __str__ returned non-string (type NoneType)Process finished with exit code 1