Detailed explanation of the exception handling tutorial in Python, detailed explanation of the python tutorial

Source: Internet
Author: User

Detailed explanation of the exception handling tutorial in Python, detailed explanation of the python tutorial

What is an exception?

An exception occurs when one Program destroys the normal flow of the program's commands. Generally, an exception is thrown when a Python script cannot be processed in some cases. An exception is a Python object that indicates an error.

When a Python script throws an exception, it must handle the exception; otherwise, it will be terminated immediately.
Handling exception:

If there are suspicious code that may cause exceptions, you can put the suspicious code in a try block to protect your program. The try block contains the following situations: the statement, followed by the code, as an elegant way to handle the problem, as much as possible.
Syntax

Here is the simple Syntax of try... else t... else block:

try:  You do your operations here;  ......................except ExceptionI:  If there is ExceptionI, then execute this block.except ExceptionII:  If there is ExceptionII, then execute this block.  ......................else:  If there is no exception then execute this block. 

Here are some key points about the above Syntax:

  • A single try statement can have multiple different statements. It is useful to include different types of exception statements in the try block.
  • You can also provide a general t clause to handle any exceptions.
  • After the limit t clause, it can include other clauses. Block does not cause an exception: code in other blocks, if executed in try.
  • In else blocks, try: block code protection is not required.

Example

Here is a simple example. This will open a file and write it into the file and remove it normally:

#!/usr/bin/pythontry:  fh = open("testfile", "w")  fh.write("This is my test file for exception handling!!")except IOError:  print "Error: can\'t find file or read data"else:  print "Written content in the file successfully"  fh.close()

This produces the following results:

Written content in the file successfully

Example:

Here is a simpler example. It tries to open a file that has no permission and writes content to it, so it will throw an exception:

#!/usr/bin/pythontry:  fh = open("testfile", "r")  fh.write("This is my test file for exception handling!!")except IOError:  print "Error: can\'t find file or read data"else:  print "Written content in the file successfully"

This produces the following results:

Error: can't find file or read data

There is no exception in the limit t clause:

You can also use different definitions as follows:

try:  You do your operations here;  ......................except:  If there is any exception, then execute this block.  ......................else:  If there is no exception then execute this block. 

The try-retry t statement captures all exceptions. Using this try-catch t statement is not considered a good programming habit, but because it captures all exceptions, it does not enable programmers to find the root cause of a possible problem.
Multiple exceptions in the limit t clause:

You can also use the same division statement to handle multiple exceptions, as shown below:

try:  You do your operations here;  ......................except(Exception1[, Exception2[,...ExceptionN]]]):  If there is any exception from the given exception list,   then execute this block.  ......................else:  If there is no exception then execute this block. 

Try-finally statement:

You can use finally: block together with try: block. Whether the try block causes an exception or no code finally block is a required block. The try-finally statement syntax is as follows:

try:  You do your operations here;  ......................  Due to any exception, this may be skipped.finally:  This would always be executed.  ......................

Note that the T clause or finally clause can be provided, but cannot be used at the same time. The else clause and finally clause cannot be used at the same time.
Example:

#!/usr/bin/pythontry:  fh = open("testfile", "w")  fh.write("This is my test file for exception handling!!")finally:  print "Error: can\'t find file or read data"

If you do not have the permission to open the file as a write, the following results are generated:

Error: can't find file or read data

In the same example, you can write data more concisely, as shown below:

#!/usr/bin/pythontry:  fh = open("testfile", "w")  try:   fh.write("This is my test file for exception handling!!")  finally:   print "Going to close the file"   fh.close()except IOError:  print "Error: can\'t find file or read data"

When an exception is thrown in a try block, the execution is immediately passed to the finally block. All the statements in the finally block are executed, and the exception is thrown again. If the handle T statement appears at a higher layer, try-again t statements.
Exception parameter:

An exception may have a parameter, which is a value that provides other information about this problem. The parameter is changed according to the exception content. You can use different clauses to provide a variable, as shown below to capture abnormal parameters:

try:  You do your operations here;  ......................except ExceptionType, Argument:  You can print value of Argument here...

If you are writing code to handle an exception, you can declare a variable according to the Exception name. If you capture multiple exceptions, you can have a variable following the exception tuples.

This variable will receive abnormal values that mainly contain exceptions. This variable can receive one or more values in the form of a tuples. This tuples usually contain error strings, error codes, and an error location.
Example:

The following is an example of an exception:

#!/usr/bin/python# Define a function here.def temp_convert(var):  try:   return int(var)  except ValueError, Argument:   print "The argument does not contain numbers\n", Argument# Call above function here.temp_convert("xyz");

This produces the following results:

The argument does not contain numbersinvalid literal for int() with base 10: 'xyz'

Throw an exception:

You can use the raise statement to throw several exceptions. Generally, the syntax of raise statements.
Syntax

raise [Exception [, args [, traceback]]]

Here, Exception is the Exception type (for example, NameError) and parameter is the parameter value used for Exception. This parameter is optional. If not provided, the parameter of the exception is None.

The last traceback parameter is optional (and rarely used in practice). If it exists, it is used for exception backtracking objects.
Example:

An exception can be a string, a class, or an object. Most Python core throws are classes, and some parameters are considered as class instance exceptions. It is easy to define new exceptions. For more information, see:

def functionName( level ):  if level < 1:   raise "Invalid level!", level   # The code below to this would not be executed   # if we raise the exception

Note: In order to catch an exception, the "escape T" statement must reference the exception that throws the same class object or a simple string. For example, to catch the above exception, you must write the limit t clause, as shown below:

try:  Business Logic here...except "Invalid level!":  Exception handling here...else:  Rest of the code here...

User-defined exceptions:

In Python, you can also create your own exceptions through the built-in exception standard derived class.

The following is an example of RuntimeError. Here is the class created from the RuntimeError subclass. It is useful to capture an exception when you need to display more details.

In the try block, a user-defined exception is thrown and caught in the limit t block. Variable e is used to create an instance with a Networkerror class.

class Networkerror(RuntimeError):  def __init__(self, arg):   self.args = arg

Therefore, once the class defined above is used, an exception can be thrown as follows:

try:  raise Networkerror("Bad hostname")except Networkerror,e:  print e.args

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.