Concise Python tutorial --- 13. Exception Handling
An exception occurs when some exceptions occur in your program. For example, if you want to read a file that does not exist. Or, when the program runs, it is accidentally deleted. Exceptions can be used to handle the above situations.
Error
Consider a simple print statement: Print "hello ". Assume that you write print as Pring. Then an error is thrown:
>>> Python Pring "hello ";
File "<stdin>", line 1
Python Pring "hello ";
^
Syntaxerror: Invalid Syntax
>>>
From the above output, we can see that the error information is printed in detail, and the output error information is completed by the error processor.
Try... try t
Use the try... retry t statement to handle exceptions. We place the common statements in the try-block and the error handling statement in the Fail T-block.
Import sys;
Try:
S = raw_input ('Please input a integer :');
Num = int (s );
Print num;
Failed t eoferror:
Print U "isn't it? Do not input anything directly? ";
Except t:
Print U "incorrect input ";
Print U "execution completed. ";
Note that an else clause can be added after the try... limit t statement. This else clause is called when no exception occurs.
Exception
An exception is thrown using the raise statement. You must also specify the error/Exception name and the exception object triggered with the exception. The errors or exceptions you can cause should be a direct or indirect export class of the error or exception class.
For example, define an exception and then throw it in the program.
Class stringlengthisnot6exception (exception ):
Def _ init _ (self, S, Len ):
Exception. _ init _ (Self)
Self. S = s
Self. Len = Len
Try:
S = raw_input ("enter a string :")
If Len (s )! = 6:
Raise stringlengthisnot6exception (S, Len (s ))
Except t stringlengthisnot6exception, E:
Print e. s, "is not length 6, but", E. Len
Else:
Print "no exception was raised ."
Try... finally
What should you do if you want to close the file regardless of whether an exception occurs? This can be done using finally blocks. Note: In a try block, you can use the limit t clause and the Finally block. If you want to use them at the same time, you need to embed one into another.
Try:
F = file ("C:/abc.txt ");
While true:
Line = f. Readline ();
If Len (line) = 0:
Break;
Print line;
Finally:
F. Close ();
Print U "to close the file. ";