13th Chapter exception
The exception occurs when there are some abnormal conditions in your program.
Error
If we misspelled print to print, pay attention to uppercase, so Python throws a syntax error.
A syntaxerror is thrown and the detected error location is printed out. This is the fault of this error handler for the work done.
Try: Except
We try to read a user's input. Press Ctrl-z (Linux users Press ctrl-d) to see what happens.
Python raises an error called eoferror, which basically means it finds an unexpected end of the file (represented by Ctrl-z)
Handling Exceptions
You can use try: The except statement handles the exception, the try-block puts the usual statement, and the except-blocks the error-handling statement.
#-*-coding:utf-8-*-#Filename:try_except.pyImportSYSTry: S= Raw_input ('Enter something --')exceptEoferror:Print '\nwhy did you do a EOF on me?'sys.exit ()#Exit The programexcept: Print '\nsome error/exception occurred.' #Here , we aren't exiting the programPrint ' Done'
Put all the statements that could throw errors in the try block and handle all errors and exceptions in the EXCEPT clause/block.
Except clauses can be specialized in handling 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 clause, there is at least one associated except clause.
If an error or exception is not handled, the default Python processor is called. It stops the program from running and prints a message.
You can also make try. The catch block is associated with the last else clause. When no exception occurs, the ELSE clause is executed.
Throw exception
Throws an exception using the Raise statement. Also specify the name of the error/exception and the exception object that accompanies the exception, and the error or exception that is thrown should be either a direct or indirect export class for the error or Exception class, respectively.
#-*-coding:utf-8-*-#Filename:raising.pyclassshortinputexception (Exception):" "A user-defined Exception class." " def __init__(self,length,atleast): Exception.__init__(self) self.length=length Self.atleast=atleastTry: S= Raw_input ('Enter something --') ifLen (s) < 3: RaiseShortinputexception (Len (s), 3) #Other work can continue as usual hereexceptEoferror:Print '\nwhy did you do a EOF on me?'exceptshortinputexception, x:Print 'shortinputexception:the input was of length%d, is excepting at least%d'%(X.length, X.atleast)Else: Print 'No exception was raised'
Here we customize the new exception type Shortinputexception class, with two fields--length the length of the given input, atleast is the minimum length the program expects.
In the EXCEPT clause, the error class and the variable used to represent the error/exception object are provided. This is similar to the concept of formal parameters and arguments in function calls. We use the length and atleast fields of the exception object to print an appropriate message for the user.
Try: Finally
Finally blocks are bound to be executed. Under a try block, you can use both the EXCEPT clause and the finally block, and you need to embed one in the other.
#-*-coding:utf-8-*-#Filename:finally.pyImport TimeTry: F= File ('Poem.txt') whileTrue:#Our usual file-reading idiomline =F.readline ()ifLen (line) = =0: BreakTime.sleep (2) PrintLine ,finally: F.close ()Print 'cleaning up...closed the file.'
We intentionally paused for 2 seconds with the Time.sleep method before printing a line, making the program run slower. When the program runs, press CTRL-C interrupt/Cancel program to trigger the KEYBOARDINTERRUPT exception. But before the program exits, the finally clause is still executed and the file is closed.
A Byte of Python Note (11) Exception: try. Except, try. Finally