Python Exception Handling Example detailed _python

Source: Internet
Author: User
Tags exception handling finally block generator numeric python script

One, what is abnormal?
An exception is an event that occurs during program execution and affects the normal execution of the program.
In general, an exception occurs when Python does not handle the program properly.
The exception is a Python object that represents an error.
When the Python script has an exception we need to capture it, or the program terminates execution.
Ii. Exception Handling
You can use the Try/except statement to catch exceptions.
The try/except statement is used to detect errors in a try statement block, allowing the except statement to catch exception information and handle it.
If you don't want to end your program in the event of an anomaly, just capture it in a try.

Exception Syntax:
The following is a simple try....except...else syntax:

Copy Code code as follows:
Try
< statements > #运行别的代码
Except < name:
< statement > #如果在try部份引发了 ' name ' exception
Except < name >,< data:
< statement > #如果引发了 ' name ' exception to obtain additional data
Else
< statements > #如果没有异常发生

Try works by saying that when a try statement is started, Python marks it in the context of the current program so that it can be returned when the exception appears, the TRY clause executes first, and what happens depends on whether the exception occurs at execution time.

If an exception occurs when a try statement executes, Python jumps back to the try and executes the first except clause that matches the exception, and the control flow passes through the entire try statement (unless a new exception is thrown when the exception is handled).
If an exception occurs in the statement after the try, but there is no matching except clause, the exception is submitted to the upper try, or to the top of the program (This will end the program and print the default error message).
If no exception occurs when the TRY clause executes, Python executes the statement after the Else statement (if there is an else), and then the control flow passes through the entire try statement.

Exception Handling Instance 1:
The following is a simple example that opens a file in which content is written and no exception occurs:

Copy Code code as follows:
#!/usr/bin/python

Try
FH = open ("Testfile", "W")
Fh.write ("This is Me 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 ()


The above program output results:
Copy Code code as follows:
Written content in the file successfully

exception Handling Instance 2:
The following is a simple example that opens a file in which content is written to the content, but the file does not have write permission and an exception occurred:
Copy Code code as follows:
#!/usr/bin/python

Try
FH = open ("Testfile", "W")
Fh.write ("This is Me test file for exception handling!!")
Except IOError:
print "error:can\ ' t find file or read data"
Else
Print "Written content in the file successfully"


The above program output results:
Copy Code code as follows:
Error:can ' t find file or read data

Third, use except without any exception type

You can use except without any exception type, as in the following example:

Copy Code code as follows:

Try
your operations here;
......................
Except
If there is no exception, then execute this block.
......................
Else
If there is no exception then execute this block.

The above method try-except the statement to catch all occurrences of the exception. But this is not a good way, we can not identify the specific exception information through the program. Because it captures all the exceptions.
Iv. using except with a variety of exception types
You can also use the same except statement to handle multiple exception information, as follows:
Copy Code code as follows:
Try
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.

v. try-finally statements
The try-finally statement executes the last code, regardless of whether an exception occurs.
Copy Code code as follows:
Try
< statements >
Finally
< statements > #退出try时总会执行
Raise

Note: You can use a except statement or a finally statement, but both cannot be used at the same time. Else statement cannot be used concurrently with the finally statement

try-finally Usage Examples:

Copy Code code as follows:
#!/usr/bin/python

Try
FH = open ("Testfile", "W")
Fh.write ("This is Me test file for exception handling!!")
Finally
print "error:can\ ' t find file or read data"


If the file you open does not have writable permissions, the output looks like this:
Copy Code code as follows:
Error:can ' t find file or read data

The same example can be written in the following ways:
Copy Code code as follows:
#!/usr/bin/python

Try
FH = open ("Testfile", "W")
Try
Fh.write ("This is Me test file for exception handling!!")
Finally
Print "Going to close" file
Fh.close ()
Except IOError:
print "error:can\ ' t find file or read data"


When an exception is thrown in a try block, the finally block code is executed immediately.
After all the statements in the finally block are executed, the exception is raised again and the except block code is executed.
The contents of the parameter are different from the exception.

Six, the parameters of the exception
An exception can be taken with parameters and can be used as an exception information parameter for the output.
You can use the except statement to catch the parameters of the exception, as follows:

Copy Code code as follows:
Try
your operations here;
......................
Except Exceptiontype, Argument:
You can print value of Argument ...

The exception value that the variable receives is usually contained in the statement of the exception. A variable in a tuple's form can receive one or more values.
Tuples usually contain error strings, error numbers, and error locations.
The following is an instance of a single exception:
Copy Code code as follows:
#!/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");


The results of the above procedures are as follows:
Copy Code code as follows:
The argument does not contain numbers
Invalid literal for int () with base: ' XYZ '

To trigger an exception using raise:
We can use the raise statement to trigger the exception ourselves

The raise syntax format is as follows:

Copy Code code as follows:
raise [Exception [, Args [, Traceback]]]

The exception in the statement is the type of the exception (for example, the Nameerror) parameter is an exception parameter value. The parameter is optional, and if not provided, the exception is "None".
The last parameter is optional (rarely used in practice) and, if present, is the tracking exception object.
Raise usage Examples:
An exception can be a string, a class, or an object. Most of the exceptions provided by the Python kernel are instantiated classes, which are parameters of an instance of a class.
Defining an exception is very simple, as follows:
Copy Code code as follows:
def functionname (level):
If level < 1:
Raise "Invalid level!", Level
# The code below to this would is executed
# If we raise the exception

Note: To be able to catch exceptions, the "except" statement must use the same exception to throw the class object or string.
For example, we capture the above exception, and the "except" statement looks like this:
Copy Code code as follows:
Try
Business Logic here ...
Except "Invalid level!":
Exception Handling here ...
Else
Rest of the code here ...

VII. user-defined exception instances
By creating a new Exception class, the program can name their own exceptions. Exceptions should be typically inherited from exception classes, by direct or indirect means.
The following is an instance related to RuntimeError, in which a class is created and the base class is RuntimeError, which is used to output more information when an exception is triggered.
In a try statement block, a user-defined exception executes the EXCEPT block statement, and the variable e is the instance used to create the Networkerror class.

Copy Code code as follows:
Class Networkerror (RuntimeError):
def __init__ (self, arg):
Self.args = arg

After you have defined the above class, you can trigger the exception as follows:
Copy Code code as follows:
Try
Raise Networkerror ("bad hostname")
Except Networkerror,e:
Print E.args


attached: Python standard exception
Baseexceptiona: base class for all exceptions
SYSTEMEXITB python: Interpreter request exit
KEYBOARDINTERRUPTC: User interrupts execution (usually input ^c)
Exceptiond: base class for general errors
Stopiteratione: No more values for iterators
Generatorexita: Generator (generator) unexpected exception to notify exit
Systemexith:python Interpreter Request Exit
Standarderrorg: base class for all built-in standard exceptions
Arithmeticerrord: base class for all numeric calculation errors
Floatingpointerrord: Floating-point calculation error
Overflowerror: Numeric operation exceeds maximum limit
Zerodivisionerror: Except (or modulo) 0 (all data types)
Assertionerrord: Assertion statement failed
Attributeerror: Object does not have this property
Eoferror: No built-in input, arrival EOF Mark
Environmenterrord: base class for operating system errors
IOError: Input/output operation failed
Oserrord: Operating system error
WINDOWSERRORH Windows: System call failed
Importerror: Failed to import module/object
KEYBOARDINTERRUPTF: User interrupts execution (usually input ^c)
Lookuperrord: base class for invalid data query
Indexerror: There is no such index in the sequence (index)
Keyerror: This key is not in the map
Memoryerror: Memory overflow error (not fatal for the Python interpreter)
Nameerror: Object not declared/initialized (no attributes)
UNBOUNDLOCALERRORH: Access to uninitialized local variables
Referenceerrore: Weak reference (Weak reference) attempting to access an object that has been garbage collected
RuntimeError: General Run-time errors
Notimplementederrord: Methods that have not yet been implemented
Syntaxerror:python syntax error
Indentationerrorg: Indentation Error
Taberrorg:tab and Space Mixing
Systemerror General Interpreter System error
TypeError: Operations that are not valid for type
ValueError: Invalid arguments passed in
Unicodeerrorh:unicode-related errors
Error when decoding the Unicodedecodeerrori:unicode
Unicodeencodeerrori:unicode encoding Error
Unicodetranslateerrorf:unicode Conversion Error
WARNINGJ: base class for warnings
DEPRECATIONWARNINGJ: Warning about deprecated features
Futurewarningi: Warning of changes in the construction of future semantics
OVERFLOWWARNINGK: Old warning about automatic promotion to long int
Pendingdeprecationwarningi: Warnings about features that will be discarded
RUNTIMEWARNINGJ: Warning of suspicious run-time behavior (runtime behavior)
SYNTAXWARNINGJ: Warning of questionable grammar
USERWARNINGJ: Warning for user code generation

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.