Abnormal:
- Exception (Exception): Occurs because of a run-time error, resulting in a traceback
- "Traceback" is a detailed description of the run-time errors that occur
Common exceptions: (To be perfected)
- ValueError occurs when data does not conform to the expected format
- Ioerroe occurs when data is not properly accessed (for example, your data file may be moved or renamed)
- Nameerror, the name of the variable being called does not exist
Handling Exceptions:
- The Try/except statement provides an exception handling mechanism to protect some code that might cause a run-time error
- The pass statement is a Python empty statement or a null statement, and it does nothing
Such as
Try
Code #可能出现异常需要保护的语句 (can be multiple lines)
Except: #冒号前可以加具体的error名称 to exclude specific exceptions, such as ValueError
Pass #如果出现一个运行时错误, or execute the statement (whatever happens at run time, the Try statement catches all exceptions and processes, ignoring the error with pass)
Finally
1 Try:2 Print('ABC')3 Print(ABC)#There is no variable ABC, so it will be reported here Namevalue4 Print('1')#The above encountered an exception, will not execute this line, directly execute the contents of except after5 exceptNameerror:6 Pass7 finally:8 Print('2')#whether the code between try/except runs correctly or if an exception occurs, the finally group is executed, regardless of whether the exception is nameerror or not, the contents of the finally group will always run.
Output:
ABC2
Show the wrong content
The above code does not show what really happened.
Try: Print('ABC') Print(ABC)Print('1')exceptNameerror as ERR:#assigning error content to variable str Print('Error is', str (ERR))#to add STR to convert the type of err to a stringfinally: Print('2')
Output:
is ' ABC ' is not defined2
Python Learning-Basics-Exception handling