Welcome to python Data Scientist

【 Key points 】

1. Try, except, else, finally, raise Keyword 2. 3. Abnormal processing try/except/else/finally composed of several kinds of exception handling model

From the previous section we saw the entire framework for Python exceptions. This section details the syntax patterns for exception encoding, try/except/else and try/finally.

Let’s review the try, except, else, finally keywords:

The try is followed by the indented statement code, which represents the statement’s main action: the program code it is trying to execute.

There is then one or more except clauses to identify the exception to be caught, except clauses that define the exception handler thrown within the try block,

Finally, there is an optional else clause that provides the statement to execute if no exception occurs.

Discuss the following cases separately:

If an exception does occur during the execution of the try block statement, Python jumps out of the try and executes the first statement that matches the except clause that raised the exception. When an except block finishes execution, control passes to the entire try block.

If the exception occurs within the try block with no except clause, the exception is passed to the top level, forcing Python to terminate the program and print the default error message.

If the statement executed below the first line of the try does not fail, Python executes the statement under the else line, and control continues throughout the entire try statement.

In other words, the except clause catches exceptions that occur when the try block is executed, while the else clause executes only when no exception occurs when the try block is executed.

Except is focused on exception handlers: catching exceptions that occur only in statements within the relevant try code block. However, because the try block statement can call functions written elsewhere in the program, the source of the exception may lie outside the try statement itself.

A few notes about the except clause:

The except clause can list a set of exceptions [except (E1,e2,e3)] in parentheses, and if the except clause does not list the exception name after it, i.e. Except:, all exception types are captured.

However, empty except can also cause design problems. While convenient, it is possible to catch unexpected system exceptions that have nothing to do with program code, and it is possible to accidentally intercept exceptions from other processors. For example, in Python, exceptions are raised even when the system leaves the call, and obviously you usually want those events to pass.

Python introduced an alternative to this problem by catching an Exception named Exception, which has almost the same effect as an empty except:, but ignores exceptions related to system exit.

Let’s see what the try/else statement does

It may not be immediately obvious what the else clause is for, but if you think about it, without an else, you can’t tell whether the control flow passed the try statement, whether no exception was raised, or whether an exception occurred and was handled. It’s hard to tell without an else clause.

Look again at the try/finally statement

Try contains the finally clause, and Python must execute its block of code after the try statement, regardless of whether an exception occurs when the block is executed.

With this variant, Python executes the block of statement code under the first line of the try. What happens next depends on whether an exception occurs in the code block:

If the try block runs without an exception, Python jumps to execute the finally block and continues execution after the entire try statement.

If an exception occurs while the try block is running, Python will still run the finally block, but it will then pass the exception up to the higher try statement or the top-level default exception handler, and the program will not continue execution under the try statement. That is, even if an exception occurs, a finally block will still execute. Unlike except, finally does not terminate the exception, but rather throws an exception after the finally block has executed.

The try/finally form is useful when you want to be certain that an action will occur after some program code executes, no matter what the program’s abnormal behavior is. In practice, this allows you to define cleanup actions that are bound to occur, most intuitively using finally to close files and disconnect servers in the event of an exception.

Finally let’s look at the complete form: try/except/else/finally

try:

    main-action

except Exception1:

    handler1

except Exception2:

    handler2

.

else:

    else-block

finally:

    finally-block

Copy the code

Let’s go through it from the beginning:

As usual, the main-action code in this statement executes first. If the program code raises an exception, all except blocks are tested one by one for statements matching the exception thrown, handler1 is executed if Exception1 is raised, Handler2 is executed if Exception2, and so on. If no exception is thrown, else-block is executed. No matter what happened before, finch-block is executed when the main-action block is complete and any raised exceptions have been handled. In fact, even if a new exception is raised due to an error in the exception handler or else block, the program code in finch-block still executes. As mentioned earlier, the finally clause does not terminate an exception: when finch-block is executed, if the exception still exists, it will continue after the finch-block is executed, and control will jump to other parts of the program, such as our default top-level handler.

Finally, try statements must have an except or finally. Else is optional, but if there is an else, there must be at least one except.

Finally, let’s talk about Raise briefly

To explicitly raise an exception, use the raise statement, which is fairly simple in its general form. The raise statement consists of: raise+ An optional class or an instance of the class to be raised.

If you pass a class, Python calls the class without the constructor argument to create an instance of the raised class. This format is equivalent to adding parentheses after a class. It’s still essentially passing an object.

Let’s look at an example: For the IndexError we’ve seen so often before, the following two forms are equivalent,

raise IndexError

raise IndexError()

Copy the code

Raises an instance of the specified exception class, with the first form implicitly creating the instance.

When using the following syntax forms

try:

    pass

except IndexError as e:

    print(e.args)

Copy the code

In essence, the captured exception object is given the variable name E, so that the data of the exception instance and methods in the exception class can be conveniently accessed.

Python Data Scientist: