Beginning python from novice to professional study Note 10: exception

Source: Internet
Author: User
Tags integer division

0. The most important built-in exception
Exception: The base class of all exceptions.
Attributeerror: attribute reference or assignment Error
Ioerror: attempts to read or write a file that does not exist.
Indexerror: use index that does not exist in sequence
Keyerror: Use a key that does not exist in mapping
Nameerror: variable name not found
Syntaxerror: syntax error
Typeerror: Use the Error Type in built-in functions
Valueerror: Type pair, but the value is incorrect
Zerodivisionerror: Division by zero

1. custom exception
Class somecustomexception (exception): Pass

2. Capture exceptions
Try: <br/> X = input ('Enter the first number: ') <br/> Y = input ('Enter the second number :') <br/> Print x/y <br/> alias t zerodivisionerror: <br/> Print "the second number can't be zero! "

# Suitable for human-computer interaction

3. No parameter raise to throw an exception reraises
Class muffledcalculator: <br/> muffled = 0 <br/> def calc (self, expr): <br/> try: <br/> return eval (expr) <br/> condition t zerodivisionerror: <br/> If self. MUFFLED: <br/> Print 'division by zero is illegal '<br/> else: <br/> raise

# Suitable for inter-program interaction

# Note that when dividing by zero and muffled is not zero, the return value of the program is none.

4. Multiple exception branches
Try: <br/> X = input ('Enter the first number: ') <br/> Y = input ('Enter the second number :') <br/> Print x/y <br/> alias t zerodivisionerror: <br/> Print "the second number can't be zero! "<Br/> couldn't typeerror: <br/> Print" That wasn't a number, was it? "<Br/>

5. capture multiple exceptions at the same time in a sentence
Try: <br/> X = input ('Enter the first number: ') <br/> Y = input ('Enter the second number :') <br/> Print x/y <br/> Reset T (zerodivisionerror, typeerror ): # brackets actually act as tuple. <br/> Print 'your numbers were bogus... '<br/>

6. capture multiple at the same time, and identify which one is specific
Try: <br/> X = input ('Enter the first number: ') <br/> Y = input ('Enter the second number :') <br/> Print x/y <br/> Reset T (zerodivisionerror, typeerror), E: # E indicates the actually captured one <br/> Print e <br/>
7. Catch all exceptions
Try: <br/> X = input ('Enter the first number: ') <br/> Y = input ('Enter the second number :') <br/> Print x/y <br/> comment T: <br/> Print 'something wrong happened... '<br/>

However, this capture method is dangerous because it ignores errors that you did not expect in the program and cannot handle them. Therefore, try to capture all exceptions in the following way:

Try: <br/> X = input ('Enter the first number: ') <br/> Y = input ('Enter the second number :') <br/> Print x/y <br/> Except t exception, E: <br/> Print e # or do something about e <br/>

8. When all is well
I don't know what to do. I keep prompting for the input until everything is ready.
While 1: <br/> try: <br/> X = input ('Enter the first number: ') <br/> Y = input ('Enter the second number: ') <br/> value = x/y <br/> Print 'x/Y is', value <br/> Except t exception, E: <br/> Print 'invalid input: ', e <br/> Print 'Please try again' <br/> else: <br/> Break <br/>
9. Finally
Perform cleanup after possible exceptions
X = none # initialize X because del X causes an exception <br/> try: <br/> X = 1/0 <br/> finally: <br/> Print 'cleaning up... '<br/> del X <br/>

Result: --->
Cleaning up...
Traceback (most recent call last ):
File "C:/Python/Div. py", line 4, in?
X = 1/0
Zerodivisionerror: integer division or modulo by zero

You can also add the following rule t:
X = none <br/> try: <br/> X = 1/0 <br/> failed t exception, E: <br/> Print e <br/> finally: <br/> Print 'cleaning up... '<br/> del X <br/>

Result: --->
Integer Division or modulo by zero
Cleaning up...

10. Exception tracking
If an exception is thrown inside function a but not handled, it will be passed to function B that calls it. If it is not processed at function B, it will continue to be passed back, if the function g in the global domain is not processed yet, the entire program halt and displays the error message (a stack trace ):
Def faulty (): <br/> raise exception ('Something is wrong ') <br/> def ignore_exception (): <br/> faulty () <br/> def handle_exception (): <br/> try: <br/> faulty () <br/> failed t: <br/> Print 'exception handled '<br/>
Ignore_exception () --->
Traceback (most recent call last ):
File '<stdin>', line 1, in?
File '<stdin>', line 2, in ignore_exception
File '<stdin>', line 2, in faulty
Exception: Something is wrong

Handle_exception () --->
Exception handled # As long as it is processed in any location, the entire program will not be halt because of this exception.

11. The Zen of exceptions-exception Philosophy
Compare the following two codes:
Def describeperson (person): <br/> Print 'description of ', person ['name'] <br/> Print 'Age :', person ['age'] <br/> If 'occupation' In Person: <br/> Print 'occupation :', person ['occupation'] </P> <p> def describeperson (person): <br/> Print 'description ', person ['name'] <br/> Print 'Age: ', person ['age'] <br/> try: Print 'occupation :', person ['occupation'] <br/> cannot t keyerror: Pass <br/>

The first part searches for the key "Occupation" twice, and then determines the value at a time. The second part of the Code only needs one time.
However, in most cases, using try/exception or if/else is just a matter of personal preferences (a matter of taste ). It has little impact on performance, and the second place in programming is performance.

The point is that using a try/modify t statement is in your cases much more natural (more "pythonic") than if/else. Use it whenever possible.

Reference Grace Hopper's words of wisdom, "it's easier to ask forgiveness than permission ."

This policy is called leap before you look idiom.

Related Article

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.