Try capture by Python orProgramExceptions
Raise manually raises an exception
Why use exceptions?
1. error handling. When Python checks errors that run as a program, an exception is thrown. You can capture and handle these errors in the program, or ignore them.
2. Event Notifications and exceptions can also serve as signals of certain conditions, without the need to send results signs in the program or explicitly test them.
3. Handle special situations. Sometimes, some situations rarely occur.CodeException Handling is better.
4. A fancy control flow. Exceptions are a high-level "Goto" that can be used as the basis for achieving a fancy control flow. Such as reverse tracking.
Basic exception knowledge
There are two try statements in Python: one is to handle exceptions (try/try t/else ), one is to execute the final code (try/finally) regardless of whether an exception occurs ).
try/release T/else style
try:
# Run other codes
release T :
# If a 'name' exception is thrown in the try part
alias T , :
# If a 'name' exception is thrown, obtain the additional data.
else:
# If no exception occurs
when a try statement is started, Python marks it in the context of the current program, in this way, when an exception occurs, you can return here. The try clause is executed first, and what will happen next depends on whether an exception occurs during execution.
1. If an exception occurs when executing the try statement, python will jump back to try and execute the first limit t clause that matches the exception. The Exception Processing is complete, the control flow uses the entire try Statement (unless a new exception is thrown when an exception is handled ).
2. If an exception occurs in the statement after try, but no matching limit t clause exists, the exception will be submitted to the try clause on the upper layer, or to the top of the Program (this will end the program and print the default error information ).
3. If no exception occurs during the execution of the try clause, python will execute the statement after the else Statement (if else exists) and then control the flow through the entire try statement.
Try/finally Style
Try:
<Statement>
Finally:
<Statement> # Always execute when you exit try
Raise
Python always executes the finally clause, regardless of whether an exception is thrown when the try clause is executed.
1. If no exception occurs, Python runs the try clause, followed by the finally clause, and then continues.
2. If an exception occurs in the try clause, python will return to execute the finally clause and submit the exception to the upper try. The control flow will not pass the entire try statement.
Try/finally is useful when you want to make sure that some code is executed regardless of whether an exception occurs.
Raise
To cause an exception, you need to write the raise statement. The format is very simple. The raise is followed by the exception to be thrown.
Raise <Name> # manual exception
Raise <Name>, <DATA> # transmits an additional data
What is an exception name? It may be a built-in exception (such as indexerror) in the built-in scope, or any string object in your program.
Example 1:
Default behavior: displays the error message.
$ Python test. py
Traceback (innermost last ):
File "test. py", line 3, in?
A = 1/0
Zerodivisionerror: integer division or modulo
When an uncaptured exception occurs, Python ends the program and prints a stack trace information, along with the exception name and additional information.
Use try to capture built-in exceptions
If you don't want to end your program when an exception occurs, just capture it in try.
#! /Usr/bin/Python
Try:
A = 1/0
Print
Except t:
Print 'I get the error'
When the program runs, it will capture an error and execute the code after the handler T.
Abnormal usage
Exceptions are not always bad. For example, the read method of a file object returns an empty string at the end of the file. Python also provides a built-in function raw_input, which reads data from the standard input stream. Unlike the read method, raw_input () triggers a built-in eoferror at the end of a file. Therefore, you can use the following code:
While 1:
Try:
Line = raw_input () # Read rows from stdin
Failed t eoferror:
Break # exit the loop at the end of the file
Esle:
Other processing code
Success signals passed with exceptions
Found = 'item found'
Def search ():
Raises or returns found
Try:
Search ()
Except t found:
Successful
Else:
Fail
You can use try to debug the code. You can use your own exception handling to replace the default Exception Handling in Python. Encapsulate the entire program in an external try, and you can catch any exceptions during the runtime.
Exception Capture Mode
Try statement clause form table
Failed T: capture all exceptions
Failed t name: only capture specific exceptions
Failed t name, value: capture exceptions and its additional data
Failed T (name1, name2): Catch any listed exceptions
Else: If no exception exists
Finally: Always Execute
When one of the multiple exceptions is captured, Python looks at the alias t clause from top to bottom. Multiple exceptions listed in brackets are the same as those listed separately, but they are more concise.
Runtime nested exception. python will match the latest nested T.
The finally clause is executed no matter how it is executed, so it is a good place to clear the action, such as closing a file.