Basic Python Tutorial Chapter 8th: Unusual Learning Notes

Source: Internet
Author: User

section of the article refer to: http://www.runoob.com/python/python-exceptions.html

Active Throw Exception:

class myexception (Exception):     Pass # equivalent to throw in C + +, active throw exception Raise MyException

>>>

Traceback (most recent):
File "hello.py", line 4, <module>
Raise MyException
MyException

Use Dir to list all functions in the module:

Import Exceptions Print dir (exceptions)

All exception classes are listed:

>>>
[' Arithmeticerror ', ' assertionerror ', ' attributeerror ', ' baseexception ', ' buffererror ', ' byteswarning ', ' Deprecationwarning ', ' eoferror ', ' environmenterror ', ' Exception ', ' floatingpointerror ', ' futurewarning ', ' Generatorexit ', ' IOError ', ' importerror ', ' importwarning ', ' indentationerror ', ' indexerror ', ' keyerror ', ' Keyboardinterrupt ', ' lookuperror ', ' memoryerror ', ' nameerror ', ' notimplementederror ', ' oserror ', ' overflowerror ', ' Pendingdeprecationwarning ', ' referenceerror ', ' runtimeerror ', ' runtimewarning ', ' standarderror ', ' StopIteration ', ' SyntaxError ', ' syntaxwarning ', ' systemerror ', ' systemexit ', ' taberror ', ' TypeError ', ' unboundlocalerror ', ' Unicodedecodeerror ', ' unicodeencodeerror ', ' unicodeerror ', ' unicodetranslateerror ', ' unicodewarning ', ' UserWarning ' , ' ValueError ', ' Warning ', ' windowserror ', ' zerodivisionerror ', ' __doc__ ', ' __name__ ', ' __package__ ']

To customize the exception class, you only need to inherit from the exception class.

Catching Exceptions:

Try :     = Input ("")    print 3/ nexcept  Zerodivisionerror:    print"Div Zero Error"

>>>
Input number:1
3
>>>
Input number:0
Div Zero Error

The exception continues to throw at the top:

defFun (n):Try:        Print5 INexceptZerodivisionerror:Print "Fun::error"        #continue throwing up the exception        Raise            defmyfun ():Try: N= Input ("Input Number:") Fun (n)exceptZerodivisionerror:Print "Myfun::error"myfun ()

>>>
Input number:0
Fun::error
Myfun::error

Multiple except clauses and one try block capture multiple exceptions:

defmyfun ():Try: x= Input ("input x number:") y= Input ("Input y number:")        PrintX/yPrint "Hello"    #multiple except blocks    exceptZerodivisionerror:Print "Zerodivisionerror"    exceptTypeError:Print "TypeError"defFun ():Try: x= Input ("input x number:") y= Input ("Input y number:")        PrintX/yPrint "Hello"    #captures two exceptions simultaneously    except(Zerodivisionerror, TypeError):Print "Zerodivisionerror or TypeError"Fun ()

Input x Number:3
Input y number:1
3
Hello
>>>
Input x Number:3
Input y number:0
Zerodivisionerror or TypeError
>>>
Input x Number:3
Input y number: "A"
Zerodivisionerror or TypeError

Catch Exception object: If the program has the ability to log error logs, get to the exception object, and then call the object's logging method

defFun ():Try: x= Input ("input x number:") y= Input ("Input y number:")        PrintX/yPrint "Hello"    #captures two exceptions simultaneously    except(Zerodivisionerror, TypeError), e:Print "Zerodivisionerror or TypeError"        PrintEfun ()

>>>
Input x Number:3
Input y number:0
Zerodivisionerror or TypeError
Integer division or modulo by zero

Exception full capture:

Try: x= Input ("x:") y= Input ("y:")    PrintX/yexceptZerodivisionerror:Print "Zerodivisionerror"exceptTypeError:Print "TypeError"exceptException, E:#except:    Print "Other Error"    PrintE
 whileTrue:Try: x= Input ("intput x:") y= Input ("intput y:")        PrintX/y#The dead loop receives the user input and outputs the result    exceptException:Print "Exception"    #If the exception continues to loop, otherwise it exits the loop    Else:         Break

Finally: Statements that are bound to be executed regardless of whether an exception occurs

 #   like Java, there's a finally keyword in Python  Span style= "color: #0000ff;" >try  : X  = input ( " x:   )   3/ x  except   Exception:  print   " exception   finally  :  print   "  I was executed   

>>>
X:1
3
I was executed.
>>>
x:0
Exception
I was executed.

An exception can be taken with parameters that can be used as the output exception information parameter, which can be captured by the except statement to the exception parameter:

Try :   your operations here;   ...................... except Exceptiontype, Argument:    print value of Argument here ...

The exception value that the variable receives is usually contained in the exception's statement. In a tuple's form, a variable can receive one or more values. Tuples typically contain error strings, error numbers, and error locations.

 #   Define a function here.  def   Temp_convert (Var):  try  :  return   Int (Var)  except   ValueError, Argument:  print   " the argument does not contain numbers\n   " , Argument  #   call above function here.  Temp_convert ( xyz  ); 

>>>
The argument does not contain numbers
Invalid literal for int. () with base: ' XYZ '

Try works by starting a try statement, and Python is tagged in the context of the current program so that when an exception occurs, it can go back here, the TRY clause executes first, and what happens next depends on whether an exception occurs at execution time.

If an exception occurs when the statement after the try is executed, Python jumps back to the try and executes the first except clause that matches the exception, and the control flow passes through the entire try statement (unless a new exception is thrown when the exception is handled).

If an exception occurs in the statement after the try, but there is no matching except clause, the exception will be submitted to the upper try, or to the top of the program (This will end the program and print the default error message).

If no exception occurs when the TRY clause executes, Python executes the statement after the Else statement (if there is else), and then the control flow passes through the entire try statement.

In some cases, conditional statements can implement the same functionality as exceptions, but conditional statements may be less natural and readable, and on the other hand, using IF/ELSE implementations in some programs is better than using try/except.

Basic Python Tutorial Chapter 8th: Unusual Learning Notes

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.