Python Exception Basics

Source: Internet
Author: User
Tags assert

I. Examples of common anomalies and scenarios

1.AssertionError

Assertion failure, assertion is common in debugging (means that you do not use ┑ ( ̄д ̄) ┍)

Example:

  
def Foo (s):     = Int (s)    assert'n is zero! '    return / nfoo (0)
View Code

The above code will output assertionerror:n is zero!

Scheme:

Usually write yourself, check the setting assertion (assert) where

2.AttributeError

A property that has not been accessed by an object

Example:

  
' 123 ' Str_a.decode ()
View Code

The above code will output: attributeerror: ' str ' object has no attribute ' decode '

Scheme:

Check the error corresponding line, and the corresponding object. General error will have the type of the prompt object.

3.IOError

Input and output exceptions, common in file operations

Example:

  
' Hello_world.txt '  'r') f.read () f.close ()
View Code

The above code will output:

Python2:ioerror: [Errno 2] No such file or directory

Python3:filenotfounderror: [Errno 2] No such file or directory

Scheme:

Check file, file path, file operation permissions

4.IndexError

Index exception, typically an index out of range

Example:

  
List1 = [1, 2, 3]print(list1[3])
View Code

The above code output Indexerror:list index out of range

Scheme:

Check the value of the corresponding type of object for the corresponding location. For example, do you get a blank list? Debug or print to see.

Or did you get a different value than you expected? Isn't there a traitor in many of the lists that are neatly formatted?

5.ImportError

Module or Package Introduction error

The whole error is common, not an example.

Scheme:

Check if the package is not installed? Does Python have different versions of the same feature module?

Is there a problem with the case of the module name? Module path right?

6.IndentationError

The code is not aligned correctly

Example:

  
List1 = [1, 2, 3print(list1)
View Code

Scheme:

Check indentation. Is the next line in the colon not indented? Does the same code block have the same number of indented cells? Did you use the tab indent and the space problem?

7.NameError

Object not declared/initialized, property does not exist

Example:

  
Print A
View Code

Scheme:

Python does not have to declare variables to check for initialization. Also, take a look at the scope.

In the class, check that the property is used in the normal method and not initialized in __init__ ().

8.SyntaxError

Python syntax error

No, for example.

Scheme:

Check the various parentheses, colons and other punctuation, is not used in Chinese punctuation? Is there a problem with the full-width half angle?

Look at the python environment and the version is wrong, like using print in Python3.

9.TypeError

Type error

Example:

  
' 1 ' Print (NUM1 + 1)
View Code

Scheme:

Check the type used. is the number when the string? Is the parameter passed wrong?

10.WindowsError, OSError, Systemerror

System call failed, operating system error, interpreter system error

Check that the interpreter has no problem with operating system permissions there is no

Second, handling exception statements

Python handles exception-related statements try, except, else, finally

1.try:
Catching exceptions, snapping to exceptions and transferring to except processing

The sense that a piece of code will have an exception when it snaps.

2.except:

Handles exceptions, handles caught exceptions, enters the statement block when an exception occurs in a try

Can be associated with an exception type, such as except Nameerror, handling only the corresponding type of exception, the type is wrong, the exception continues to throw

Python2 in except Nameerror,e:

Python3 except Nameerror as E:

What's the exception when you're not with the type?

can be nested multiple, from top to bottom one match

When you don't want to handle it, pass it.

3.else:
Executes without exception, enters the statement block if no exception occurs in the try

4.finally:
Executes when the try is exited, regardless of whether an exception exits the try.

Paired with try, one try can have only one, and multiple try can have multiple finally in a program.

Finally can also be executed when the program exits abnormally, because when the exception exits, the try does not catch the exception correctly, but the try has attempted to capture the attempt, and then it executes finally when exiting the try and then throws the exception up.

Third, exception processing order

Exceptions are captured from the inside out and thrown up one layer at a level. If you do not catch the error.

Such as:

Try

# He didn't catch me and Catch Me #

Try

# I'll catch you first #

Except Exception:

# There's a problem with me, I'm not going to throw the pot on my back #

Except

# I'm dealing with a problem that's not caught, and the pot can't handle it.

Else

# no problem, just for me,

# If there's a problem, I'll watch you shake the pot quietly

Finally

# Anyway, let me summarize.

Iv. Manually throwing Exceptions

1. Statement raise

Raise can be followed by exceptions or not with

Raise throws an exception after execution, in general the program terminates

Use try...except ... Statement catch raise throws an exception that is treated like a normal exception

  

2. Reasons for manually throwing an exception

1) You like it, you throw an exception.

2) If you don't let anyone else do that, you're throwing an exception.

3) This is unreasonable, I'm throwing an exception

  

See a word, feel very reasonable, excerpt:

All exceptions are unsolicited, but not the one you throw.

Python's exceptions, for example, are Python's initiative, and Python as a person like us, but it's making the rules of the game.

Actively throwing exceptions depends on the situation. There are many things that can be used in making rules, testing, terminating programs, and so on.

  

Five, custom exceptions

Use a class to inherit exception to customize exceptions

Exception is the base class for the exception class, and Baseexception is the base class for exception.

For example

  
class myexception (Exception):     Pass Try :     Raise MyException ('hello! ' )except  myexception as E:    print(Type (e))      Print(e)
View Code

Custom exceptions, like Python-defined exceptions, are used.

  

  

 

Python Exception Basics

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.