Python's exception

Source: Internet
Author: User
Tags stack trace

8.1 What is an exception

Python uses an exception object to represent an exception condition. An exception is thrown when an error is encountered. If the exception object is not processed or snapped, the program terminates execution with the so-called backtracking (an error message):

>>>1/0

Error


If the error message is the full functionality of the exception, then it does not have to exist. In fact, each exception is an instance of a class that can be thrown, and can be captured in many ways, so that the program can catch the error and handle it instead of having the entire program fail.


8.2.1 Raise statements

To throw an exception, you can call the raise statement using either a class (a subclass of exception) or an instance parameter. When you use a class, the program automatically creates instances. In the following example, the built-in exception exception class is used:

>>>raise Exception

Common exception

>>>raise Exception (' abc ')

Report ABC exception error


You can use the Dir function to list the contents of a module

>>>import exceptions

>>>dir (Exceptions)

[' Arithmeticerror ', ' assertionerror ', ' Attributeerror ',...]

All these anomalies can be used in raise.


>>>raise Arithmeticerror


8.2. Custom exception Classes

Class Somecustomexception (Exception):p


8.3 Catching exceptions

Try

x = input (' Enter the first number: ')

y = input (' Enter the second number: ')

Print x/y

Except Zerodivisionerror:

Print "The second number can ' t be zero"

If no exception is caught, it is propagated to the called function. If there is still no catch, these exceptions will float to the top of the program. This means that you can catch exceptions that are thrown in other people's functions.


Class Muffledcalculator:

muffled = False

Def calc (self,expr):

Try

return eval (expr)

Except Zerodivisionerror:

If self.muffled:

print ' Division by zero ' illegal '

Else

Raise

Catching an exception, but trying to re-throw it (passing an exception), you can use a raise statement without parameters.


The following is a sample usage of this class that turns the mask on and off, respectively:

>>>calculator = Muffledcalculator

>>>calculator.calc (' 10/2 ')

5

>>>calculator.calc (' 10/0 ')

Error

>>>calculator.muffled = True

>>>calculator.calc (' 10/0 ')

When the calculator does not turn on the masking mechanism, the zerodivisionerror is captured but passed.


8.4 More than one except clause

Try

Print 2/' 0 '

Except Zerodivisionerror:

print ' divisor cannot be 0 '

Except Exception:

print ' Other types of exceptions '


8.5 Catching two exceptions with one block

If you need to catch multiple exceptions with one block, you can list them as tuples:

Try

Print 2/' 0 '

Except (Zerodivisionerror,typeerror):

print ' An exception has occurred '


8.6 Getting exceptions

Try

Print 2/' 0 '

Except (zerodivisionerror,exception) as E:

Print E

In python3.0, the EXCEPT clause is written except (Zerdivisionerror,typeerror) as E.


8.7 Catching all exceptions

Try

Print 2/' 0 '

Except

print ' Something wrong happened. ‘

Doing so is dangerous because it hides all the errors that programmers have not thought of and are not ready to handle.


8.8 Applying loops in the anomaly

Try

print ' A simple task '

Except

print ' What? Something went weong? '

Else

print ' Ah ... It went as planned. '


Use the ELSE clause:

While True:

Try

x = input (' Enter the first number: ')

y = input (' Enter the second number: ')

Value = x/y

print ' x/y is ', value

Except

print ' Invalid input,please try again. '

Else

Break

The loop here only exits without exception handling. In other words, whenever an error occurs, the program constantly asks for a re-entry.


You can use an empty except clause to catch exceptions for all exception classes (and also to catch exceptions for all of its subclasses). It is impossible to catch all exceptions, because the code in the Try/except statement can be problematic, such as using an old-style string exception or a custom exception class that is not a subclass of the exception class. However, if you need to use except exception, you can use the Print method to display the error message:

While True:

Try

x = input (' Enter the first number: ')

y = input (' Enter the second number: ')

Value = x/y

print ' x/y is ', value

Except Exception,e:

print ' Invalid input: ', E

print ' Please try Again '

Else

Break


8.9 finally clause

The last finally clause, which can be used to clean up after a possible exception. It is used in conjunction with the TRY clause:

x = None

Try

x = 1/0

Finally

print ' Cleaning up ... '

del X

In the preceding code, the finally clause is bound to be executed, regardless of whether an exception occurs in the clause try clause.

Using the DEL statement to delete a variable is a very irresponsible cleanup, so the finally clause is useful for closing a file or network socket. You can also combine try,except,finally and else in the same statement.

Try

1/0

Except Nameerror:

Print "Unknown variable"

Else

Print "That went well!"

Finally

Print "Cleaning up."


8.10 Exceptions and functions

If an exception is thrown inside a function without being processed, it propagates to the place where the function is called. If the exception is not handled there, it will continue to propagate and reach the main program (global scope). If there is no exception handler, the program will abort with the stack trace:

>>>def Faulty ()

Raise Exception (' Something is wrong ')

>>>def ignore_exception ():

Faulty ()

>>>def handle_exception ():

Try

Faulty ()

Except

print ' Exception handled '

>>>ignore_exception ()

Error

>>>handle_exception ()

Exception handled

As you can see, the exceptions produced in faulty are propagated through faulty and ignore_exception, resulting in a stack trace. Similarly, it spreads to handle_exception, but is handled by try/except statements in this function.


8.11 Unusual Zen

def describeperson (person):

print ' Description of ', person[' name ']

print ' Age: ', person[' age ']

Try

print ' Occupation: ' + person[' occupation ']

Except Keyerror:pass

Here, when printing a career, use a plus sign instead of a comma, or the string ' Occupation: ' will be output before the exception is thrown.

This program directly assumes that the ' occupation ' key exists. If he does exist, it will be more convenient. The direct fetch value is printed out. There's no need to check if it really exists. If the key does not exist, a Keyerror exception is thrown and captured by the except clause.


When you see whether an object has a specific attribute:

Try

Obj.write

Except Attributeerror:

print ' The object is not writeable '

Else

print ' The object is Writeeable '


This article is from the "linux_oracle" blog, make sure to keep this source http://pankuo.blog.51cto.com/8651697/1661442

Python's 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.