This is the 28th day of my participation in Gwen Challenge

Retrospective review

An exception occurs when a Python program fails to run due to an unknown condition.

When the program is abnormal, we catch the exception way, through the preset logic code to keep the program running, this process is called exception handling.

Exception handling is the process by which we preconfigure code to continue execution in the face of possible errors in the program code.

How do you do exception handling in Python?

The commonly used exception handling structure is as follows:

1. try.. An except construction

try.. Except is the most common exception handling construct.

Try: monitored statement block except BaseException [as E]: exception processing statement blockCopy the code

The try block contains code that can raise exceptions, while the except block is used to catch and handle exceptions

At execution time, if no exception is raised in the try block, the except block is skipped and execution continues

At execution time, if an exception occurs in a try, subsequent code in the try block is skipped to the corresponding except block to handle the exception

After the exception is handled, continue to execute the subsequent code

try:
    print("Step1")
    a = 3/0
    print("Step2")
except BaseException as e:
    print("Step3")
    print(e)
print("Step4")
Copy the code

2. try… Multiple except structures

It is generally recommended to catch as many exceptions as possible (in the order of subclass before superclass) and write exception handling code that is specific to them. To avoid leaking out possible exceptions, you can add a BaseException at the end.

Try: monitored statement block that may cause exceptions Exception Exception1: Statement block that processes Exception1 Exception Exception2: Statement block that processes Exception2..... Exception BaseException: Block of statements that handle exceptions that might be missedCopy the code

try: A = input("please input Divisor :") b = input("Please input divisor :") c = float(a)/float(b) print(c) except ZeroDivisionError: Except TypeError: print(" exception: cannot convert letter string to number ") except NameError: Except BaseException ase: print(e)Copy the code

3. The structure of the else

try… except.. The else structure adds an else block.

  • If no exception is thrown in the try block, the else block is executed.
  • If an exception is thrown in a try block, an except block is executed, not an else block
Try: a = input("please input divisor :") b = input("Please input divisor :") C = float(a)/float(b) except BaseException ase: Print (e) else: print(",c) print("game over")Copy the code
  • Send exception execution (except block executed, else not executed)

  • No exception execution is sent (execute try block, else)

4. The finally structure

try… except.. In a finally structure, the finally block is executed whether or not an exception occurs.

Usually used to free resources requested in a try block, such as closing a file after opening it

Finally Execution logic diagram is as follows:

Try: a = input("please input divisor :") b = input("Please input divisor :") C = float(a)/float(b) except BaseException ase: Print (e) else: print("finally: print ",c) finally: print("finally statement ") print("game over")Copy the code

5. Customize exceptions

When we work in practice, we sometimes need to define our own exception classes.

  1. Custom Exception classes are generally run-time exceptions that can be inherited from Exception or its subclasses.
  2. Names are usually suffixed with Error and Exception.
  3. User-defined exceptions are actively raised by the Raise statement
class AgeException(Exception): def __init__(self,errInfo): __init__(self) self.errInfo = errInfo def __str__(self): return STR (self.errInfo)+", age is not 0~150 years old! if __name__ == "__main__": age = int(input("please input age:")) if age < 0 or age > 150: raise AgeException(age) else: print("right age",age)Copy the code

conclusion

In this installment, we have studied 5 methods of exception handling in detail, which we choose to use according to our own needs in working use scenarios.

However, the exception handling itself is to warn the code of risk in advance, we must eliminate the exception, do not stay in our code, increase the risk of code problems, improve the stability of the code.

Ok, this is the content of this issue, welcome to comment, like and follow, see you next time ~