9.python Exception Handling

Source: Internet
Author: User

ONE. errors and exceptions in Python.

first, say what is wrong.

There are two types of errors in Python

    1. Syntax errors this syntax error is simply not over the Python interpreter the following are syntax Errors.

      Example 1:

      If

Output

File "/users/macbook/pycharmprojects/untitled1/job 2/test2.py", Line 1

If

^

Syntaxerror:invalid syntax

Example 2:

def test:

Pass

Example 3:

Class Foo

Pass

All of these are grammatical errors

2. Logic error

#用户输入不完整 (E.G. null Input) or illegal input (input not a number)

Num=input (">>:")

int (num)

# Unable to complete calculation

res1=1/0

res2=1+ ' str '


And then, to say what's unusual,

The so-called exception is the error signal that is emitted when the program is Running.

first, we enter a description in the Python interpreter that explains what is not Recognized.

>>>asdkjsdkjhaslk

The result is an exception thrown

Traceback (most recent): #Traceback is an unusual tracking message

File "/tmp/test2.py", Line 2, <module>

Asdkjsdkjhaslk

Nameerror:name ' ASDKJSDKJHASLK ' is not defined

The Nameerror is an exception class.

Name ' ASDKJSDKJHASLK ' is not defined this is the value of the Exception.


So when the interpreter throws an exception message, the exception is probably made up of three Parts.

    1. Tracking Information.

    2. The Exception class Name.

    3. The exception Value.


Two. common exception class that comes with Python.

Attributeerror tried to access an object that does not have a tree like foo.x but Foo has no attribute x

IOError Input/output exception is basically unable to open the file

Importerror cannot introduce a module or package is basically a path problem or a name error

Indentationerror syntax error sub-class code not aligned correctly

Indexerror index is out of sequence boundaries such as when X has only three elements but tries to access x[5]

Keyerror attempts to access keys that do not exist in the dictionary

Keyboardinterrupt CTRL + C is pressed

Nameerror using a variable that has not been assigned to an object

SyntaxError Python code Illegal code can not compile (personally think this is a syntax error is wrong to write

TypeError incoming object types are not compliant with the requirements

Unboundlocalerror attempting to access a local variable that has not been set is basically due to another global variable with the same name

Cause you think you're accessing it

ValueError incoming a caller does not expect a value even if the type of the value is correct

Note that these are just some of the more common inside exception classes in Python that are not all


Three. Exception Handling

    1. What is exception handling

      The first, when the Python interpreter detects that a program has an error, triggers an exception. of course, programmers can also use raise to manually trigger an Exception. In other words, the program executes to a result that the programmer does not want, can use raise to trigger an exception to let the program terminate Manually.




The second programmer writes specific code to catch an Exception. That is, one step of the program triggers an exception exception. once the entire Python program is triggered it terminates when the programmer does not want the exception to be triggered by using the try and except to catch the exception to ignore the assumption that the program will still function when the exception is Triggered.

When the exception capture succeeds, it goes into another processing branch and executes the logic you customized for it so that the program does not crash this is exception handling.



2. How to do exception handling

There are two points to be clear before handling the Exception.

The exception of the 1th program is caused by an error.

2nd syntax error and exception handling It's okay. This syntax error must be corrected before the program runs

2.1 Use if to determine to handle exceptions

First we can run the following code First.

#-*-coding:utf-8-*-

#第一段代码

Num1=raw_input (' >>: ') #输入一个字符串试试

int (num1)

#第二段代码

Num2=raw_input (' >>: ') #输入一个字符串试试

int (num2)

#第三段代码

Num3=raw_input (' >>: ') #输入一个字符串试试

int (num3)

Executing the above code will trigger a VALUEERROR exception once the exception is triggered the program will exit after the code is not Executed.

Next use the If judgment to handle the exception

#-*-coding:utf-8-*-

Num1=raw_input (' >>: ') #输入一个字符串试试

If Num1.isdigit ():

int (num1) #我们的正统程序放到了这里, The rest belongs to the exception handling category

Elif Num1.isspace ():

print ' input is a space, just execute my code here '

elif len (num1) = = 0:

print ' input is empty, just execute my logic code here '

Else

print ' Other situation, execute my logic code here '

Since if judgment can handle exceptions then why is it that almost no one uses the if judgment to handle the exception?

Using the If method we only add exception handling for the first piece of Code. for the second piece of code you have to re-write a bunch of ifelif ...

of course, you can merge it into one piece, but you'll find that the readability of the code is very, very poor.


Note that when you use the If judgment to deal with an exception, you will encounter a more disgusting problem, take the example above. the first code and the second code encounter the same exception is valueerror, according to normal thinking to think of the same error You can handle it once, but if you use if the If judgment condition of the two code is different, you can only force you to write a new if judgment to deal with the exception of the second piece of code ... The third paragraph ... Fourth paragraph ... Fifth paragraph ... The cycle ... The code that handles the exception you write slowly ....

2.2 Use Python to handle exceptions in a mechanism that specializes in handling exceptions.

In fact, within python, a specialized exception class is customized for each exception and can be understood as the type of exception and then provides a specific syntax structure to handle exceptions Specifically.

This grammatical structure is the basic syntax structure of try and except as follows

Try

Blocks of code being detected

Except exception type

The logic to execute this position once an exception is detected in the try


Know the basic syntax next look at an example of handling exceptions

The following code throws an exception directly if it does not handle the Exception.

S1 = ' Hello '

Try

int (s1)

Except Indexerror as E: explain the following as keyword except if you snap to indexerror this exception assigns the value of the exception directly to the

print e variable e


2.3 Catching multiple exception multi-branch catch exceptions at the same time

S1 = ' Hello '

Try

int (s1)

Except Indexerror as E:

Print (e)

Except Keyerror as E:

Print (e)

Except ValueError as E:

Print (e)


24,000 can be abnormal.

There is a universal exception in Python's exception exception he can catch arbitrary exceptions.

Example

S1 = ' Hello '

Try

int (s1)

Except Exception as E:

Print (e)


Four. analyze the application scenarios of universal anomaly and Multi-Branch Anomaly.

Situation one if the effect you want is that no matter what happens we uniformly discard or use the same piece of code logic to handle them then this time using exception (universal exception Class) is a good choice.

Example 1

S1 = ' Hello '

Try

int (s1)

Except Exception,e:

' Discard or perform other logic '

Print E

#如果你统一用Exception没错是可以捕捉所有异常但意味着你在处理所有异常时都使用同一个逻辑去处理这里说的逻辑即当前expect下面跟的代码块


Situation Two if the effect you want is for different exceptions we need to customize different processing logic then we need to use multiple Branches.

Example 2

S1 = ' Hello '

Try

int (s1)

Except Indexerror as E:

Print E

Except Keyerror as E:

Print E

Except ValueError as E:

Print E


Multi-Branch exception handling can also be used in conjunction with a universal exception

S1 = ' Hello '

Try

int (s1)

Except Indexerror as E:

Print E

Except Keyerror as E:

Print E

Except ValueError as E:

Print E

Except Exception as E: This is a universal anomaly.

Print E


FIVE. additional structure descriptions for try exception snapping.

Python's Try code block also has two knowledge points that are not described as the Else Branch and finally branch of the try Code BLOCK.

When there is no exception in the code block in try, the code under the Else branch is Executed.

The code block in the finally is executed regardless of whether the code execution of the code block in the try has an Exception.

finally, It is generally used to do some cleanup operations.

The following are examples of else and finally use

S1 = ' Hello '

Try

int (s1)

Except Indexerror as E:

Print E

Except Keyerror as E:

Print E

Except ValueError as E:

Print E

#except Exception as E:

# Print E

Else

print ' Try inside code block no exception ' execute me '

Finally

print ' will execute the module, usually for cleanup, whether it is abnormal or not



Six. Trigger the exception manually.

Using the Raise keyword, you can trigger an exception type manually, even if there are no errors.

An exception that is triggered manually with the Raise keyword can also be captured by a try.

The following is an example of a manual trigger exception that is used when writing Iterators.

After throwing an stopiteration exception

Class C1:

def __init__ (self,start,stop):

Self.start = Start

Self.stop = Stop

def __iter__ (self):

return self

def next (self):

If Self.start >= self.stop:

Raise stopiteration manually triggered a stopiteration Exception.

n = Self.start

Self.start + = 1

return n

O1 = C1 (1,10)

For I in O1:

Print I

Catch yourself triggering the exception yourself

Try

Raise TypeError (' type error ')

Except Exception as E:

Print E


Seven. Customize the exception class.

Custom exceptions There's Nothing to say about inheriting an exception from the base class. here is an example.

#_ *_coding:utf-8_*_

Class TestException (baseexception):

def __init__ (self,msg):

Self.msg=msg

def __str__ (self):

Return self.msg

Try

Raise TestException (' type error ')

Except TestException as E:

Print E


Eight. Assertions.

An ASSERT keyword is required to make assertions in Python.

Assertion is, in a sense, like a lite version of If judgment

Assert 1 = = 1 condition is true when no exception is triggered the program can continue to Run.

Assert 1 = = 2 The conditional expression does not trigger a Assertionerror exception for True.



Nine. finally Added.

Under what circumstances use Tryexcept to catch an exception

A simple sentence should be added tryexcept other logic errors should be corrected as far as possible, except in the case of unforeseen anomalies.

In addition, tryexcept must be used Sparingly.


This article is from the "rebirth" blog, make sure to keep this source http://suhaozhi.blog.51cto.com/7272298/1921000

9.python Exception Handling

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.