Python errors and exceptions

Source: Internet
Author: User
This article introduces Python errors and exceptions concepts Python errors and exceptions (total)

1. how to handle errors and exceptions

  1. Common errors
  2. A: NameError

  3. If True: SyntaxError

  4. F = oepn('1.txt '): IOError

  5. 10/0: ZeropisionError

  6. A = int ('D'): ValueError

  7. Program running interrupted: KeyboardInterrupt

2. Python-use try_cmdt to handle exceptions (1)
try:    try_suiteexcept Exception [e]:    exception_block
  1. Try is used to capture errors in try_suite and deliver the errors to the retry T for processing.

  2. T is used to handle exceptions. if The exception is the same as the caught exception, use exception_block to handle the exception.

# case 1try:    undefexcept:    print 'catch an except'
# case 2try:    if undefexcept:    print 'catch an except'
  • Case1: exception can be caught because it is a running error.

  • Case2: Exceptions cannot be caught because of syntax errors and pre-running errors.

--

# case 3try:    undefexcept NameError,e:    print 'catch an except',e
# case 4try:    undefexcept IOError,e:    print 'catch an except',e
  • Case3: exception can be caught because an exception occurs when NameError is caught.

  • Case4: Exceptions cannot be caught. NameError is not handled because IOError is set.

Example
import randomnum = random.randint(0, 100)while True:    try:        guess = int(raw_input("Enter 1~100"))    except ValueError, e:        print "Enter 1~100"        continue    if guess > num:        print "guess Bigger:", guess    elif guess < num:        print "guess Smaller:", guess    elif guess == num:        print "Guess OK,Game Over"        break    print '\n'
3. Python uses try_cmdt to handle exceptions (2)
  • Try-try T: handle multiple exceptions

try:    try_suiteexcept Exception1[e]:    exception_block1except Exception2[e]:    exception_block2except ExceptionN[e]:    exception_blockN
4. use Python-try_finally
try:    try_suitefinally:    do_finally
  • If the try statement does not capture errors, the code executes the do_finally statement.

  • If the try statement captures errors, the program first executes the do_finally statement and then submits the captured errors to the python interpreter for processing.

5. Python-try T-else-finally
 try:    try_suite except:    do_except finally:    do_finally
  • If the try statement does not capture exceptions, run finally after the try code segment is executed.

  • If try catches an exception, execute wait t to handle the error first, and then execute finally

6. Python-with_as statement
with context [as var]:    with_suite
  • The with statement is used to replace the try_effect_finall statement to make the code more concise.

  • The context expression returns an object.

  • Var is used to save the context returned object. a single return value or ancestor

  • With_suite uses the var variable to operate the context returned object

The with statement is essentially context management:
  1. Context Management Protocol: inclusion method__enter__()And__exit()__To implement the two methods for objects that support this protocol

  2. Context manager: defines the runtime context to be established when the with statement is executed. it is responsible for the entry and exit operations in the context of the with statement block.

  3. Enter the context manager: call the manager__enter__METHOD. if the as var statement is set, the var variable accepts__enter__()Method return value

  4. Exit the context manager: call the manager__exit__Method

class Mycontex(object):    def __init__(self, name):        self.name = name    def __enter__(self):        print "__enter__"        return self    def do_self(self):        print "do_self"    def __exit__(self, exc_type, exc_val, exc_tb):        print "__exit__"        print "Error:", exc_type, " info:", exc_valif __name__ == "__main__":    with Mycontex('test context') as f:        print f.name        f.do_self()
Whith statement application scenario:
  1. File operations

  2. Mutually exclusive objects between process threads, such as mutex locks

  3. Other objects supporting context

2. standard exceptions and automatic exceptions 1. Python-assert and raise statements
  • Rais statement

    • The reise statement is used to actively throw an exception.

    • Syntax format: raise [exception [, args]

    • Exception: exception class

    • Args: a tuple that describes the exception information.

raise TypeError, 'Test Error'
raise IOError, 'File Not Exit'
  • Assert statement

    • Asserted statement: The assert statement is used to check whether the expression is true. if the expression is false, an AssertionError occurs.

    • Syntax format: assert expression [, args]

    • Experession: expression

    • Args: description of the judgment condition

assert 0, 'test assert'
assert 4==5, 'test assert'
2. Python-standard and custom exceptions
  • Standard Exception

    • Python built-in exception, which exists before the program is executed

  • Custom exception:

    • Python allows custom exceptions to describe exceptions that are not involved in python.

    • Custom exceptions must inherit the Exception class

    • Custom exceptions can only be triggered manually

class CustomError(Exception):    def __init__(self, info):        Exception.__init__(self)        self.message = info        print id(self)    def __str__(self):        return 'CustionError:%s' % self.messagetry:    raise CustomError('test CustomError')except CustomError, e:    print 'ErrorInfo:%d,%s' % (id(e), e)


For more articles about Python errors and exceptions, refer to PHP!

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.