Python exception handling summary, python exception handling

Source: Internet
Author: User

Python exception handling summary, python exception handling

This article details common exception handling in Python for your reference. The details are as follows:

1. Throw an exception or custom exception

Python uses an exception object to indicate exceptions. An exception is thrown when an error occurs. If the exception object is not processed or captured, the program terminates the execution with the so-called trace (Traceback, an error message.

①. Raise statement

The raise keyword in Python is basically the same as the throw keyword in C # and Java, as shown below:

# -- Coding: UTF-8 -- def ThorwErr (): raise Exception ("throwing an Exception") # Exception: throwing an Exception ThorwErr ()

The raise keyword is followed by a general Exception type (Exception). In general, the more detailed the Exception is, the better. Python has many built-in Exception types in the exceptions module, you can use the dir function to view the exception types in exceptions as follows:

import exceptions# ['ArithmeticError', 'AssertionError'.....]print dir(exceptions)

Transfer exception

If an exception is caught, but you want to re-raise it (passing an exception), you can use the raise statement without parameters:

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

②. Custom exception type

You can also customize your own special types of exceptions in Python. You only need to inherit from the Exception class (either directly or indirectly:

class SomeCustomException(Exception):  pass

2. Capture exceptions

Similar to try/catch in C #, use the try/catch t keyword in Python to catch exceptions, as shown below:

# -- Coding: UTF-8 -- try: print 2/0 bytes t ZeroDivisionError: print 'division cannot be 0'

①. Capture multiple exceptions

Only the exception types declared after the rollback t statement are captured. If other types of exceptions may be thrown, an additional rollback t statement is required, you can also specify a more common Exception type, for example, Exception, as follows:

# -- Coding: UTF-8 -- try: print 2/'0' except T ZeroDivisionError: print 'division cannot be 0' except T Exception: print 'other type exception'

To capture multiple exceptions, in addition to declaring multiple failed t statements, you can also column multiple exceptions as tuples after one failed t statement:

# -- Coding: UTF-8 -- try: print 2/'0' handle T (ZeroDivisionError, Exception): print 'an Exception occurred'

②. Get exception information

Each exception has some exception information. In general, we should record the exception information:

# -- coding: utf-8 --try:  print 2/'0'except (ZeroDivisionError,Exception) as e:  # unsupported operand type(s) for /: 'int' and 'str'  print e

3. finally clause

The finally clause and try clause are used together, but unlike the limit t statement, finally executes the code in the finally clause regardless of whether an exception occurs in the try clause. In general, finally is often used to close files or in Socket.

# -- Coding: UTF-8 -- try: print 2/'0' handle T (ZeroDivisionError, Exception): print 'an Exception occurs. 'Finally: print' is executed regardless of whether an Exception occurs'

Python exception handling

Try to use either writable T or finally, and use writable t instead of finally.

Python exception handling

While True:
N = raw_input ("Input a number between 2 and 6 ")
Try:
N = int (n)
Failed t Exception:
Print "no"
Continue
If n> = 2 and n <= 6:
Print "OK", n
Else:
Print "no"
Continue

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.