Although it is called an error, it is one thing to do with exceptions in C #. It's just that Python is called a mistake (error) and C # is called an exception (Exception).
Create an exception manually first:
1 file = open ("','r')
The above sentence because the path is an empty path, so the file certainly does not exist, the execution of this sentence will cause filenotfounderror this error.
Since it is wrong, the program also stopped, which we do not want, so we have to find a way to deal with it.
In Python, exception handling uses the three keywords of try, except, finally.
Modify the code as follows:
1 path = " 2 : 3 file = open (Path, " r " ) str = File.read () 5 print 6 except : 7 print ( " there is an error ' )
After modifying the code, if the path is correct, it will output the contents of the file, if it fails, it will output there is an error
In addition, you can also add finally
1Path ="'2 Try:3File = open (path,'R')4str =File.read ()5 Print(str)6 except:7 Print('there is an error')8 finally:9 Print('End')
If the file exists, it will end in the final output.
Python learning error handling in -16.python