(Basic Python tutorial) learning notes | Chapter 2 | exception

Source: Internet
Author: User

(Basic Python tutorial) learning notes | Chapter 2 | exception

------

What is an exception: Python uses an exception object to indicate exceptions. If the exception information is not processed or captured. The program will use a response to terminate the execution.

>>> 1/0 Traceback (most recent call last): # Traceback: an error message File"
 
  
", Line 1, in? ZeroDivisionError: integer division or modulo by zero
 
Every exception is an instance of some classes. These instances can be thrown and can be captured in many ways, so that the program can capture and handle errors, rather than making the entire program fail.

Note: ZeroDivisionError: is an instance.

------

Errors in your own way

Raise statement:

To cause an exception, you can use a class or instance parameter to call the raise statement. When using a class, the program will automatically create an instance. The following is a simple example, using the built-in Exception class

# Raises a common exception without any information

>>> raise ExceptionTraceback (most recent call last):  File "
 
  ", line 1, in ?Exception
 
# A common exception with an error message is thrown.

>>> raise Exception,"This is a normal Exception"Traceback (most recent call last):  File "
 
  ", line 1, in ?Exception: This is a normal Exception
 
# This can also be written.
>>> raise Exception('System device Busy...')Traceback (most recent call last):  File "
 
  ", line 1, in ?Exception: System device Busy...
 
There are many built-in exceptions. Most of them can be found in the exceptions module. You can use dir to list the module content.
>>> dir(exceptions)['ArithmeticError', 'AssertionError', 'AttributeError', 'DeprecationWarning', 'EOFError', 'EnvironmentError', 'Exception', 'FloatingPointError', 'FutureWarning', 'IOError', 'ImportError', 'IndentationError', 'IndexError', 'KeyError', 'KeyboardInterrupt', 'LookupError', 'MemoryError', 'NameError', 'NotImplementedError', 'OSError', 'OverflowError', 'OverflowWarning', 'PendingDeprecationWarning', 'ReferenceError', 'RuntimeError', 'RuntimeWarning', 'StandardError', 'StopIteration', 'SyntaxError', 'SyntaxWarning', 'SystemError', 'SystemExit', 'TabError', 'TypeError', 'UnboundLocalError', 'UnicodeDecodeError', 'UnicodeEncodeError', 'UnicodeError', 'UnicodeTranslateError', 'UserWarning', 'ValueError', 'Warning', 'ZeroDivisionError', '__doc__', '__name__']
Note:

1. All these exceptions can be used in raise statements.

2. Some of the most important built-in exception classes


------

Custom exception class:

If the built-in exception classes cannot meet the requirements, they need to be independent of the exception classes other than exceptions, that is, custom classes.

You can add exception classes, as shown in the following pattern.

>>> class customerException(Exception): pass
# You can add a method to it.

------

Capture exceptions

Exceptions can be captured most effectively. try/try t can be used. For example, there are two distinct numbers.

>>> x = input('Enter the first number:')Enter the first number:10>>> y = input('Enter the second number:')Enter the second number:0>>> print x/yTraceback (most recent call last):  File "
 
  ", line 1, in ?ZeroDivisionError: integer division or modulo by zero.
 
To capture exceptions and handle them, rewrite the program.
>>> try:...     x = input('Enter the 1st number:')...     y = input('Enter the 2nd number:')        print x/y... except ZeroDivisionError:...     print "The second number can't be zero!"...Enter the 1st number:10Enter the 2nd number:0The second number can't be zero!
Note: If no exception is caught, it will be propagated to the function that calls it. If not captured, these exceptions will be floated to the top layer of the program,

That is to say, you can capture the exceptions caused by other functions.

------

No Parameters

If an exception is caught and you want to raise it again, you can call raise without parameters. For example, it is helpful to do so! Consider a calculator class that can block ZeroDivisionError. If this error is activated, the calculator prints an error instead of transmitting the exception. If this is used during user interaction, this is very useful. However, if an exception is thrown in the program, the blocking mechanism can be disabled. Below is the code for such a class

class MuffledCalculator:    muffled = False    def cal(self,expr):        try:            return eval(expr)        except ZeroDivisionError:            if self.muffled:                print 'Division by zero is illegal'            else:                raise

Output result

>>> c = MuffledCalculator()>>> c.cal('10/2')5>>> c.cal('10/0')Traceback (most recent call last):  File "
 
  ", line 1, in 
  
       c.cal('10/0')  File "D:\Learn\Python\Exception.py", line 13, in cal    return eval(expr)  File "
   
    ", line 1, in 
    
     ZeroDivisionError: integer division or modulo by zero>>> c.muffled = True>>> c.cal('10/0')Division by zero is illegal
    
   
  
 
------

Multiple distinct T statements

>>> x = input('Enter the 1st number:')Enter the 1st number:10>>> y = input('Enter the 2nd number:')Enter the 2nd number:'hello,world!'>>>>>> print x/yTraceback (most recent call last):  File "
 
  ", line 1, in ?TypeError: unsupported operand type(s) for /: 'int' and 'str'
 
So it should be written as follows:
try:    x = input('Enter the 1st number:')    y = input('Enter the 2nd number:')    print x/yexcept ZeroDivisionError:    print "The second number can't be zero!"except TypeError:    print "That wasn't a number, was it?"
------

Capture multiple exceptions with one click

Try: x = input ('Enter the 1st number: ') y = input ('Enter the 2nd number:') print x/y # Get all possible errors, put it in the ancestor. # note that you must use (). Otherwise, an unpredictable error occurs, including: print "Your numbers were bogus..."
------

Object capturing

If you want to access the exception object in the except T clause, you can use two parameters. For example, this function is useful if you want to keep the program running, but want to record Errors for some reason (for example, simply print them to the user. The following example can print an exception, but the program continues to run.

try:    x = input('Enter the 1st number:')    y = input('Enter the 2nd number:')    print x/yexcept (ZeroDivisionError,TypeError,NameError), e:    print eprint 'Hello,World!'
Output result:
>>> Enter the 1st number:10Enter the 2nd number:0integer division or modulo by zero'Hello,World!'>>> Enter the 1st number:10Enter the 2nd number:helloname 'hello' is not defined'Hello,World!'
Note: The representation in Python3.0 is as follows: ‑t (ZeroDivisionError, TypeError, NameError) as e

------

Real full Capture:

Even if the program can handle several exceptions, some exceptions will still slide from the bottom of the eyelids, or the division program just now. If nothing is input?

Traceback (most recent call last):  File "
 
  ", line 2, in 
  
       x = input('Enter the 1st number:')  File "
   
    ", line 0       ^SyntaxError: unexpected EOF while parsing
   
  
 
This exception escaped try/retry t, and the programmer could not predict all possible exceptions, so they could not capture all exceptions. If you want the program to capture all exceptions, you can write as follows:
try:    x = input('Enter the 1st number:')    y = input('Enter the 2nd number:')    print x/yexcept:    print "Something Wrong Happen!"
In this way, all exceptions can be captured.

WRAN: it is dangerous to capture all exceptions like this because it hides all the errors that programmers did not expect and are not ready to handle. It will also capture users' attempts to terminate the execution of CTRL + C and use the sys. exit function to terminate the program. This is because the Exception T is used. e is better, or the Exception Object e is checked.

------

Everything is fine:

Sometimes it is useful to execute a piece of code when something bad occurs. In this case, you can add an else statement like a condition or loop.

>>> try:...     print "A Simple"... except:...     print "What? Something went wrong?"... else:...     print "Ah...Runing as planed."...A SimpleAh...Runing as planed.
Use the else clause to implement the previously mentioned Loop
while True:    try:        x = input('Enter 1st number:')        y = input('Enter 2nd number:')        value = x/y        print 'x/y is:', value    except:        print 'Invalid input, please try again!'    else:        break
Output result:
>>> Enter 1st number:10Enter 2nd number:0Invalid input, please try again!Enter 1st number:10Enter 2nd number:eInvalid input, please try again!Enter 1st number:10Enter 2nd number:2x/y is: 5
Considering that capturing all exceptions is risky, you can use Exception and e to replace them and print the error information. Then the program can improve it:
while True:    try:        x = input('Enter 1st number:')        y = input('Enter 2nd number:')        value = x/y        print 'x/y is:', value    except Exception, e:        print 'Invalid input', e        print 'please try again!'    else:        break
Output result:
Enter 1st number:10Enter 2nd number:0Invalid input integer division or modulo by zeroplease try again!Enter 1st number:10Enter 2nd number:helloInvalid input name 'hello' is not definedplease try again!Enter 1st number:10Enter 2nd number:2x/y is: 5

------

Last

Finally, the finally clause can be used for possible exception cleanup, closing database links, and closing file handles. It is generally used in combination with try/finally.

x = Nonetry:    x = 1/0finally:    print "Cleaning Up..."    del x
In the above Code, the finally clause will certainly be executed, regardless of whether exceptions occur in the try clause (the reason for initializing x before the try clause is that if this is not done, due to the existence of ZeroDivisionError, x will never be assigned a value. This will cause an exception when del is used in the finally clause to delete it, and this exception cannot be captured.) run this code before the program crashes, the cleaning of variable x is complete.

Output result:

>>> Cleaning Up...Traceback (most recent call last):  File "D:\Learn\Python\Exception.py", line 72, in 
 
      x = 1/0ZeroDivisionError: integer division or modulo by zero
 
Because del is not responsible for deleting a variable, the finally clause is used to close the database link. It is very useful to close the file handle. You can also try, use t, else, and finally (or use at least three of them)
try:    1/0except Exception, e:    print eelse:    print "That's well well."finally:    print "Clean Up..."
Output result:
>>> integer division or modulo by zeroClean Up...
------

Exceptions and functions

Exceptions and functions work naturally. If an exception is thrown in a function and is not processed, it will be transmitted to the function call area. If no exception is handled anywhere, she continues to spread the program until it reaches the main program. If no exception handler exists, the program terminates with a stack trace.

>>> def faulty():...     raise Exception('Something is wrong.')...>>> def ignore_exception():...     faulty()...>>> def handle_exception():...     try:...         faulty()...     except:...         print 'Exception handled'...
Output result:
>>> ignore_exception()Traceback (most recent call last):  File "
 
  ", line 1, in ?  File "
  
   ", line 2, in ignore_exception  File "
   
    ", line 2, in faultyException: Something is wrong.>>> handle_exception()Exception handled
   
  
 
It can be seen that the exception caused by faulty () is propagated through faulty and ignore_exception (), which eventually leads to stack tracing.

Similarly, she also spread to handle_exception (), but also a function is processed by try/try t.

------

Exception Zen

Sometimes if/else implementation is better than try/else t implementation. Let's take a look at the following examples:

def describePerson(person):    print 'Description of',person['name']    print 'Age:', person['age']    if 'occupation' in person:        print 'Occupation:',person['occupation']>>> d = {'name':'Alice','age':28}>>> describePerson(d)Description of AliceAge: 28>>> d = {'name':'Alice','age':28,'occupation':'IT'}>>> describePerson(d)Description of AliceAge: 28Occupation: IT
The code is very intuitive, but the efficiency is not high. The program will search for occupation twice.

One is to check whether the key exists, and the other is to obtain the value

def describePerson(person):    print 'Description of',person['name']    print 'Age:', person['age']    try:        print 'Occupation:'+ person['occupation']    except KeyError:        pass
NOTE: In this example, the + is used to print the job, instead of the string. Otherwise, the string will be output when an exception is thrown. In this case, it is assumed that the occupation already exists. If it does not exist, it is captured in the handle T KeyError, which improves the program efficiency. try/retry T is useful when checking whether the object has a specific value.
try:    obj.writeexcept AttributeError:    print 'The object is not writeable'else:    print 'The object is writeable.'
------

Functions in this Chapter

Warning. filterwarnings (action) is used to filter warnings




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.