The exception occurs when there are some abnormal conditions in your program. For example, when you want to read a file, and that file does not exist. Or when the program is running, you accidentally delete it. These conditions can be handled using exceptions .
If there are some invalid statements in your program, Python will throw and tell you there is an error , thus handling the situation. Consider a simple print statement. If we make print Print a mistake and pay attention to capitalization, then Python throws a syntax error.
We can observe that one SyntaxError is triggered and the error location detected is also printed out. This is the fault of this error handler for the work done.
ValueError data does not match the expected format (the split () function does not find a delimiter in s?t?ri?n?g)
Try
role, words = Line.split (': ', 1)
Except ValueError:
Pass
Ioeerror data is not accessible (such as files being moved or renamed)
Try
Fdata = open ("Test.txt", ' W ')
Fmiss = open ("Est.txt", ' W ')
Pirnt Fmiss.readline ()
Except Ioeerror as err:
Print "File error:" + str (ERR)
Finally
If ' Fdata ' in Locals ():
Fdata.close ()
If ' Fmiss ' in Locals ():
Fmiss.close ()
Work with files without worrying about file closure
Try
With open (' Test.txt ', ' W ') as Fdata, open (' Est.txt ', ' W ') as Fmiss:
Print >>fdata, "Hello"
Except Ioeerror as err:
print ' File error: ' + str (ERR)
Try: Except
We try to read a user's input. Press ctrl-dto see what happens.
>>> s = raw_input(‘Enter something --> ‘)
Enter something --> Traceback (most recent call last):
File "<stdin>", line 1, in ?
EOFError
Python raises a known EOFError error, which basically means it finds an unexpected end of the file (represented by ctrl-d)
Next, we will learn how to deal with such errors.
Handling Exceptions
We can use try..except statements to handle exceptions.
We put all the statements that could throw errors in the try block, and then except handle all the errors and exceptions in the clause/block. excepta subordinate clause can handle a single error or exception, or a set of errors/exceptions that are included in parentheses. If the name of the error or exception is not given, it handles all errors and exceptions. For each try subordinate clause, there is at least one relative except clause.
If an error or exception is not handled, the default Python processor is called. It terminates the operation of the program and prints a message that we have seen in this process.
You can also have the try..except block associated with the previous else clause. When no exception occurs, the else subordinate clause will be executed.
We can also get an exception object to get more information about this exception. This is illustrated in the next example.
Throw exception
You can use a raise statement to throw an exception. You also have to indicate the name of the error/exception and the exception object that accompanies the exception firing . The error or exception that you can throw should be a Error Exception direct or indirect export class of one or class, respectively.
Here, we create our own exception types, and we can actually use any predefined exceptions/errors. This new exception type is ShortInputException class. It has two fields--the length length of the given input, which atleast is the minimum length the program expects.
In the except subordinate clause, we provide the error class and the variables used to represent the error/exception object . This is similar to the concept of formal parameters and arguments in function calls. In this particular except clause, we use the and domain of the exception object to length atleast print an appropriate message for the user.
Try: Finally
If you are reading a file, you want to close the file regardless of whether the exception occurred or not, how to do it? This can be finally done using blocks.
Note that under a try block, you can use except clauses and finally blocks at the same time . If you want to use them at the same time, you need to embed one in the other.
We do the usual work of reading the files, but I intentionally pause for 2 seconds before each line of print time.sleep . The reason for this is to make the program run slower (Python usually runs fast because of its nature). When the program is running, press ctrl-c to break/Cancel the program.
We can observe KeyboardInterrupt that the exception is triggered and the program exits. But before the program exits, the finally clause is still executed, closing the file
From:http://www.cnblogs.com/wei-li/archive/2012/03/26/2417314.html
Concise python Tutorial--c++ Programmer's Perspective (vii): exception