Welcome to python Data Scientist

【 Key points 】

1. Default handling and active capture of exceptions 2. Active triggering of exceptions and custom exceptions 3. Finally termination of code block usage

An exception is an error that occurs when a program is running.

Yes, Python throws an exception whenever a program error is detected at run time. There are two ways to handle exceptions: one is to catch and respond to errors in the program; Or ignore exceptions that have occurred.

If the exception is ignored, Python’s default exception handling behavior starts: Stop the program and print an error message. If you don’t want to enable this default behavior, you write a try statement to catch and recover from the exception. When the program detects an error, Python jumps to the try processor, and the program resumes execution after the try.

Let’s start with python’s built-in default exception handler

def fetcher(obj, index):

    return obj[index]



x = 'spam'



print(fetcher(x,3))

print(fetcher(x,9))



m

Traceback (most recent call last) :

 File "E:/12homework/12homework.py", line 7.in <module>

print(fetcher(x,9))

 File "E:/12homework/12homework.py", line 2.in fetcher

return obj[index]

IndexError: string index out of range

Copy the code

As you can see from this example, we try to index positions beyond the end of the string and raise an exception when the function tries to execute obj[9]. Python detects out-of-bounds index operations for sequences and reports them by throwing (firing) the built-in IndexError exception.

In this case, our code does not intentionally catch the exception, so it goes all the way up to the top level of the program and enables the default exception handler: print the standard error message, which is the list of lines and functions that were activated when the exception occurred.

So what if we want to catch the exception ourselves?

Because in some cases, that’s not what we want. For example, server programs generally need to keep working even when internal errors occur. If you don’t want the default exception behavior, you need to wrap the call in a try statement and catch the exception yourself.

def fetcher(obj, index):

    return obj[index]



x = 'spam'



try:

    fetcher(x,9)

except IndexError:

    print('got exception')



got exception

Copy the code

Now, when an exception is raised by execution within the try block, Python automatically jumps to the processor (the block below the except clause) to run.

def fetcher(obj, index):

    return obj[index]



x = 'spam'



try:

    fetcher(x,9)

except IndexError:

    print('got exception')

print('continue... ')



got exception

continue.

Copy the code

In this example, after we catch and handle the exception, the program continues execution after catching the entire try statement; This is why we get the continue message. We see no standard error messages, and the program will continue as normal.

In addition to python itself raising exceptions, we can also actively raise exceptions in our programs. To manually trigger an exception, you can directly execute the raise statement. Exceptions raised by users are captured in the same way as exceptions raised by Python programs:

try:

    raise IndexError

except IndexError:

    print('got exception')



got exception

Copy the code

If no exception is caught, the user-defined exception is passed up to the top level default exception handler and terminates the program with a standard error message to see if it feels familiar.

raise IndexError



Traceback (most recent call last) :

 File "E:/12homework/12homework.py", line 1.in <module>

raise IndexError

IndexError

Copy the code

We can also customize exceptions

We just used the raise statement to raise a built-in exception defined in Python’s built-in scope. It’s also possible to define a new Exception ourselves, which may require a little object-oriented knowledge, so just know that custom exceptions can be written as classes that inherit from a built-in Exception class: usually this class is called Exception

class Bad(Exception):

    pass



def doomed(a):

    raise Bad()



try:

    doomed()

except Bad:

    print('got Bad')



got Bad

Copy the code

Finally, the termination behavior finally code block

Try statements can contain finally code blocks. You can define the end behavior that must be executed at the end. By “must” I mean execute regardless of whether an exception occurs in the try block.

try:

    raise IndexError

finally:

    print('in finally')

print('after finally')



in finally

Traceback (most recent call last):

 File "E:/12homework/12homework.py", line 2.in <module>

raise IndexError

IndexError





try:

    print('ok')

finally:

    print('in finally')

print('after finally')



ok

in finally

after finally

Copy the code

As you can see from the above try/finally combination, the program will execute the statements in the finally block regardless of whether the try block is abnormal. But when an exception occurs, Python skips over to execute the behavior in finally. After executing the statement in finally, python passes the exception in the try to the default handler at the top level, so statements after finally do not execute. But if the code in the try does not raise an exception, the code block after finally continues as normal.

Let’s summarize:

In practice, a try/except combination can be used to catch exceptions and recover from them, while a try/finally combination is handy to ensure that the termination will always run regardless of whether or not the code within a try block has an exception.

An example would be to make sure that the file is closed whether or not an exception is raised and whether or not an exception is caught.

Finally we can use try/except/finally together. Try is the main function code, except is used to catch exceptions, and statements in finally are executed whether or not an exception occurs and is caught by except.

Python Data Scientist: