The user entered a non-compliant value, or the file that needs to be opened does not exist. These conditions are known as "exceptions", and a good program needs to be able to handle the exceptions that may occur, thus preventing the program from interrupting.
For example we go to open a file:
f = File (' Non-exist.txt ')
print ' File opened! '
F.close ()
If the file does not appear in the folder that should appear for some reason, the program will error:
IOError: [Errno 2] No such file or directory: ' Non-exist.txt '
The program is interrupted at the wrong place, and the subsequent print is not executed.
In Python, you can use the TRY...EXCEPT statement to handle exceptions. The idea is to put the statement that could throw the exception in the try-block and put the exception-handling statement in the except-block.
Put that piece of code into try...except:
Try
f = File (' Non-exist.txt ')
print ' File opened! '
F.close ()
Except
print ' File not exists. '
print ' Done '
When the program throws an exception while opening a file inside a try, it skips the rest of the code in the try and jumps directly to the statement handling exception in except. "File NOT exists." is then output. If the file is opened successfully, it will output "file opened!" instead of executing the statement in except.
However, the entire program will not be interrupted, and the last "done" will be output.
In a try...except statement, the exception thrown in a try is like throwing a frisbee, and except is a sensitive dog that always catches the frisbee accurately.
Python Learning Notes (exception handling)