Python base 16 (error, exception)

Source: Internet
Author: User
Tags integer division
What is an error and what is an exception

An error is an event that occurs during code execution that interrupts or interferes with the normal flow of code and creates an exception object. When an error interrupts the process, the program will try to find an exception handler (a piece of code that tells the program how to respond to the error) to help the program resume the process. In other words, an error is an event, and an exception is an object created by that event.

When the phrase "generate an exception" is used, it indicates that the method in question has an error, and an exception object (containing information about the error and when and where it occurred) is created to respond to the error. Factors that cause errors and subsequent exceptions include user errors, resource failures, and programming logic failures. These errors are related to the way the code accomplishes a specific task, not the purpose of that task.

If you do not handle exceptions, that is, do not respond to errors, the robustness of the program will be greatly reduced, and even normal operation cannot be guaranteed, so you must perform exception handling.

In project development, exception handling is indispensable. Exception handling helps people debug, and it makes it easier for people to find bugs through richer information. Exception handling can also improve the fault tolerance of a program.

Exceptions in Python

In Python, exceptions are also objects and can be manipulated. All exceptions are members of the base class Exception. All exceptions inherit from the base class Exception and are defined in the exceptions module.

Python uses exception objects to represent exceptions. When an error is encountered, an exception is thrown. If the exception object is not handled or caught, the program terminates execution with a so-called traceback (an error message):

>>> 1/0

Traceback (most recent call last):
  File "<pyshell # 0>", line 1, in <module>
    1/0
ZeroDivisionError: integer division or modulo by zero
 Go your own way

raise statement

To raise an exception, you can call the raise statement using a class (a subclass of Exception) or the number of instance parameters. The following example uses the built-in Exception class:

>>> raise Exception # raise a normal exception without any error message

Traceback (most recent call last):
  File "<pyshell # 2>", line 1, in <module>
    raise Exception
Exception
>>> raise Exception (‘hyperdrive overload’) # Added some exception error messages

Traceback (most recent call last):
  File "<pyshell # 3>", line 1, in <module>
    raise Exception (‘hyperdrive overload’)
Exception: hyperdrive overload
 

 Common built-in exception classes:

Third, catch the exception

We can use try / except to catch exceptions.

>>> try:
    res = 2/0
except ZeroDivisionError:
    print "Error: Divisor must not be zero!"

    
Error: Divisor must not be zero!
See, we really caught ZeroDivisionError! What if I want to catch and handle multiple exceptions? There are two ways, one is to pass multiple exception class parameters to an except clause, and the other is to write multiple except clauses, each clause is passed the exception class parameters you want to handle. Even these two usages can be mixed and matched!

Multiple except clauses

try:
    x = input (‘Enter the first number:‘)
    y = input (‘Enter the second number:‘)
    print x / y
except ZeroDivisionError:
    print "The second number ca n‘t be zero!"
except TypeError: # exception handling for characters
Print "Please enter a number!"

# 再来 跑:
>>>
Enter the first number: 10
Enter the second number: ‘hello, word’
Please enter a number!
 

 

 

Catching multiple exceptions in one block

If you need to catch multiple exceptions in one block, you can list them as tuples.

try:
    x = input (‘Enter the first number:‘)
    y = input (‘Enter the second number:‘)
    print x / y
except (ZeroDivisionError, TypeError, NameError): # list error types
    print "Yout numbers were bogus ..."
 

try ... except ... else statements
    Now let's talk about this else statement. There are many special else uses in Python, such as for conditions and loops. Put it in a try statement, and its effect is actually similar: when no exception is detected, the else statement is executed.

while True:
    try:
        x = input (‘Enter the first numbre:‘)
        y = input (‘Enter the second numbre:‘)
        value = x / y
        print ‘x / y is’, value
    except:
        print ‘Invalid input, please try again.’
    else:
        break # The loop here will only exit if no exception is raised
 

finally clause
The finally clause is a piece of code that will be executed regardless of whether an exception is detected. We can discard the except clause and the else clause, use try ... finally alone, or use it with except.

try:
    s = 1/0
#except Exception, e:
except ZeroDivisionError, e:
    print ‘Error:% s’% e
finally:
    print ‘ok’
 

 

The complete syntax structure is as follows:

try:
    ...
except exception1:
    ...
except exception2:
    ...
except:
    ...
else:
    ...
finally:
    ...
 

If an exception occurs in the try, the exception will be executed and the except will be executed. Exceptions are compared layer by layer to see if they are exception1, exception2 ... until they find their belonging and execute the corresponding except statement.

 

Python basics 16 (error, exception)

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.