PYTHON3 exception handling and exception types

Source: Internet
Author: User
Tags assert exception handling stack trace in python

Python Exception handling

The following is an Excel file using Python's xlrd module, which may cause exceptions, use a try to catch exceptions, handle them, prevent the program from running, and log exception information.


def save_file (file, filename):
"""
Open Excel File
"""
Try
Book = Xlrd.open_workbook (file)
Sheet = book.sheet_by_index (0)
Except Exception as E:
Logging.info (' ERROR: {0} file: {1} '. Format (e, file))
Shutil.copy2 (file, './error ' + filename)
Return False
Row_nums = Sheet.nrows
Col_nums = Sheet.ncols

The above code catches the exception and uses the logging module to log the log and uses the Shutil module to copy the exception files to another folder.

Here the common exception handling methods are listed to facilitate the usual search.

Catch Exception base class

Python3 requires our exception to inherit the Exception class. All exceptions to built-in are inherited from this class. So, we just need to capture an instance of this class and we can catch all the exceptions.

Try
Raise
Except Exception as err:
Print (ERR)

Using Sys.exc_info () and Sys.last_traceback
Sys.exc_info () returns a 3-valued meta table that contains the exception that was caught when the command was invoked.

The contents of this meta table are (type, value, Traceback), Where:

Type the type name from the acquired exception, which is a subclass of the baseexception;
The value is a captured exception instance;
Traceback is a Traceback object, which is detailed below.
Sys.last_traceback contains the same content as Sys.exc_info (), but it is used primarily for debugging purposes and is not always defined.

Import Sys
Try
Raise
Except
T,V,TB = Sys.exc_info ()
Print (T,V)

Using Traceback

The trackback module is used to accurately mimic the stack trace behavior of the Python3 parser. You should use this module as much as possible in your program.

Traceback.print_exc () can print the current exception directly.

Import Traceback
Try
Raise
Except
Traceback.print_exc ()
TRACEBACK.PRINT_TB () is used to print the Trackback object mentioned above.

Import Sys,traceback
Try
Raise
Except
T,V,TB = Sys.exc_info ()
TRACEBACK.PRINT_TB (TB)
Traceback.print_exception () can directly print the meta table provided by Sys.exc_info ().

Import Sys,traceback
Try
Raise
Except
Traceback.print_exception (*sys.exc_info ())
In fact, the following two sentences are equivalent:

Traceback.print_exc ()
traceback.print_exception (*sys.exc_info ())

A simple example

In the absence of any definition of the X variable:

Print X
Print 1

The Nameerror exception will be thrown:

Nameerror:name ' x ' is not defined

and 1 will not be output, which means the program will be interrupted. If the code changes as follows:

Try
Print X
Except Nameerror:
Print "Something is wrong!"
Print 1

The resulting output will be:

Something is wrong!
1

As you can see, the except we define "grabs" the Nameerror type of statement and executes the appropriate processing code, and the program is not interrupted.
Using raise

We can trigger the exception ourselves, for example:

Raise Indexerror

Python will return:

Traceback (most recent call last):
File "D:\ My Documents \ Desktop \todo\exep.py", line 1, in <module>
Raise Indexerror
Indexerror

Custom exceptions

The following defines a myexception class that inherits from the exception class built in Python.

Class MyException (Exception):p
Try
#some code here
Raise MyException
Except MyException:
Print "MyException encoutered"

The results are:

MyException encoutered

You can catch multiple exceptions within a except:

Except (Attributeerror, TypeError, SyntaxError):

Catch all exceptions

This except block can catch all exceptions as long as the except is not followed by any exception type.

Except

To catch an inheritance relationship for an exception

When we except super, we also catch the exception of the raise sub.
Finally

Code that executes forever, regardless of whether a try block throws an exception. Typically used to perform shutdown files, disconnect server connections, and so on.

Class MyException (Exception):p
Try
#some code here
Raise MyException
Except MyException:
Print "MyException encoutered"
Finally
Print "Arrive finally"

Results:

MyException encoutered
Arrive finally

Try, except, else

You can add an else block in a try block, and the code block executes when no exception is thrown:

Try
Print "Normal code here"
Except MyException:
Print "MyException encoutered"
Else
Print "No exception"
Finally
Print "Arrive finally"

The results are:

Normal code here
No exception
Arrive finally

raise exceptions, adding data at the same time

Raise exception, we can add some extra data, just like the following example:

Class MyException (Exception):p
Try
Raise MyException, ", and some additional data"
Except Myexception,data:
Print "MyException encoutered"
Print data

Assert assert

An assertion is one that expects the specified condition to be met, and throws a Assertionerror exception if it is not satisfied. For example:

def positive (x):
Assert x > 0
Print "X"
Positive (1)
Positive (0)

Positive (0) A sentence will throw an exception.
With/as

With/as statements are intended primarily to replace try/finally statements, often used to do some cleanup work or to clean up the site.

With open (' Test.txt ') as MyFile:
For line in MyFile:
Here #code
Here #code

When the with code block is finished, the file is automatically closed. This is because the returned object supports the context management protocol. Page 598 of the original book is about the discussion of the Protocol, such as how to customize a class that supports the protocol and thus supports the WITH statement

The exception type of Python

As follows:

EXCEPTION NAME DESCRIPTION
Exception Base Class for all exceptions
Stopiteration Raised when the "Next" () method of iterator does.
Systemexit Raised by the Sys.exit () function.
StandardError Base class for all built-in exceptions except Stopiteration and Systemexit.
Arithmeticerror Base class for all errors the occur for numeric calculation.
Overflowerror Raised when a calculation exceeds maximum limit for a numeric type.
Floatingpointerror Raised when a floating point calculation fails.
Zerodivisonerror Raised when division or modulo by zero takes to all numeric types.
Assertionerror Raised in case of failure of the Assert statement.
Attributeerror Raised in case of failure of attribute reference or assignment.
Eoferror Raised when there are no input from either the raw_input () or input () function and the "end of" the file is reached.
Importerror Raised when a import statement fails.
Keyboardinterrupt Raised when the user interrupts program execution, usually by pressing CTRL + C.
Lookuperror Base class for the all lookup errors.
Indexerror Keyerror Raised when it is not found in a sequence. Raised when the specified key isn't found in the dictionary.
Nameerror Raised when a identifier is isn't found in the local or global namespace.
Unboundlocalerror EnvironmentError Raised when trying to access a local variable in a function or is but no value has been to it. Base class for all exceptions that occur outside the Python environment.
IOError IOError Raised when a input/output operation fails, such as the print statement or the ' open ' () function when trying to open a Fil E that does not exist. Raised for operating system-related errors.
SyntaxError Indentationerror Raised when there is a error in Python syntax. Raised when indentation are not specified properly.
Systemerror Raised when the interpreter finds a internal problem, but when this error is encountered the Python interpreter does Exit.
Systemexit Raised when Python interpreter are quit by using the Sys.exit () function. If not handled in the code, causes the interpreter to exit.
Raised when Python interpreter are quit by using the Sys.exit () function. If not handled in the code, causes the interpreter to exit. Raised when a operation or function is attempted this is invalid for the specified data type.
ValueError Raised the built-in function for a data type has the valid type of arguments, but the arguments have values s Pecified.
RuntimeError Raised when a generated the error does not fall to any category.
Notimplementederror Raised when "an abstract method," needs to be implemented in a inherited class is not actually implemented.

These are the specific exception types that can catch the specified exception:


Import Sys

Try
f = open (' MyFile.txt ')
s = F.readline ()
i = Int (S.strip ())
Except OSError as err:
Print ("OS error: {0}". Format (ERR))
Except ValueError:
Print ("Could not convert data to an integer.")
Except
Print ("Unexpected error:", Sys.exc_info () [0])
Raise
Catch a specific exception type and output an exception hint.

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.