13. Abnormal
(1) Error
Some invalid statements in the program, such as syntax errors, are as follows:
1 " AA " 2 syntaxerror:invalid Syntax 3 Print " AA " 4 AA 5
(2) Try...except
1>>> s = raw_input ("Enter something --")2Enter something--and #这里期望输入, but the actual execution of Ctrl+d causes the following exception3 4 Traceback (most recent):5File"<pyshell#4>", Line 1,inch<module>6s = raw_input ("Enter something --")7 eoferror:eof When reading a line8>>>
You can use Try...except to handle exceptions
1 #-*-coding:utf-8-*-2 3 ImportSYS4 5 Try:6s = raw_input ("Enter something --")7 exceptEoferror:8 Print "\nwhy did yo do a EOF on me?"9Sys.exit ()#Exit The programTen except: One Print "\nsome error/exception occurred." A #Here , we aren't exiting the program - - Print " Done"
Output:
(3) Exception thrown
You can use a raise
statement to throw an exception .
Also specify the name of the error/exception and the exception object that accompanies the exception.
The error or exception that can be thrown should be Error
a Exception
direct or indirect export class of one or class.
1 #-*-coding:utf-8-*-2 3 4 classshortinputexception (Exception):5 """A user-defined Exception class."""6 7 def __init__(self, length, atleast):8Exception.__init__(self)9Self.length =lengthTenSelf.atleast =atleast One A - Try: -s = raw_input ("Enter something --") the ifLen (s) < 3: - Raise Shortinputexception (Len (s), 3) - #Other work can continue as usual here - exceptEoferror: + Print "\nwhy did you do a EOF on me?" - exceptshortinputexception, x: + Print "shortinputexception:the input was of length%d,was expecting at least%d"%(X.length, X.atleast) A Else: at Print "No exception was raised."
Output:
(4) try...finally
Do you want to do something without exception or not?
This can be finally
done using blocks.
Concise Python Tutorial Learn note 9