In the process of program running, there are always various problems and errors. Some errors are self-inflicted when we write code, such as syntax errors, invocation errors, and even logic errors. There are also errors that are unpredictable but entirely possible, such as file nonexistence, insufficient disk space, network congestion, system errors, and so on. These lead to abnormal interruption and exit of the program during the running process, we collectively referred to as exceptions. Most exceptions are not handled by the program, but are presented as error messages.

There are many types of exceptions, and Python has dozens of common exceptions built into it, right in the Builtins module, which you can use without special imports. Note that all exceptions are exception classes, and the first letter is capitalized!

When an exception occurs, Python prints an exception message, with the preceding section showing the context in which the exception occurred and the details in the form of a call stack. Exception types are also printed as part of the information, such as ZeroDivisionError, NameError, and TypeError.

1. Simple syntax for catching exceptions

In program development, if the execution of some code is not certain, we can add a try to catch the exception:

Try: code that is tried except: error handlingCopy the code

The try… Except… Statement handling exceptions work as follows:

  • First, execute the try clause (the statement between the keyword try and the keyword except)
  • If no exception occurs, the except clause is ignored and the try clause terminates after execution.
  • If an exception occurs during the execution of the try clause, the rest of the try clause is ignored. If the type of the exception matches the name after except, the corresponding EXCEPT clause is executed.

2. Catch exceptions based on error types

During program execution, different types of exceptions may be encountered and different responses can be made for different types. In this case, error types need to be caught.

Try: num = int(input(" except integer: ")) result = (3 / num) print(result) except ZeroDivisionError: Except ValueError: print(" please enter the correct integer ")Copy the code

3. Catch exceptions for unknown errors

It is difficult to anticipate all possible errors at development time, so you can add an Except Exception if you want your program to not be terminated by an Exception thrown by the Python interpreter, regardless of any errors.

Try: num = int(input(" except integer: ")) result = (3 / num) print(result) except ZeroDivisionError: Print (" error %s") except Exception as result: print(" unknown error %s" %result)Copy the code

Description: Exception can catch any Exception.

4. Complete syntax for exception capture

Pass except (error type 2, error type 3) Pass except Exception as result: # print(result) else: # pass except Exception as result: # Code pass that will be executed regardless of whether there is an exceptionCopy the code

Description: Else is an optional clause that must follow all except, and this clause will be executed when no exceptions occur in the try clause. There is also a finally clause, indicating that the finally clause is executed regardless of the execution of the try and except clauses.

5. Passing of exceptions

Exception passing: When a function/method executes an exception, the exception is passed to the caller of the function/method. If passed to the main program, there is still no exception handling, the program terminates.

Def demo02(): return demo01() try: print(demo02()) except ValueError: Except Exception as result: print(" unknown error %s" % result)Copy the code

6. Raise an exception

In actual development, the Python interpreter can actively throw exceptions based on business requirements, in addition to code execution errors.

At development time, if a business requirement wants to throw an Exception, you can create an Exception object and then use the raise keyword to throw the Exception object.

Def input_password(): password = input(" please input password: ") if len(password) > 8: Return password exp = Exception(" Password length is less than 8 characters ") raise exp try: user_password = input_password() print(user_password) except Exception as result: Print (" Error %s" % result) ------ Output result ------ Please enter the password: 123456 There is an error. The password length is less than 8 charactersCopy the code

7. Custom exceptions

Python has many built-in exception classes, which are derived from the BaseException class.

Here are some common exception classes to keep in mind! This allows you to quickly and accurately determine the type of exception when you see most exceptions.

Exception names explain
AttributeError An attempt was made to access a property of an object that does not exist
IOError The input/output is abnormal
ImportError Unable to import modules or packages; Most of them are path problems or name errors
IndentationError The indentation error
IndexError Index error
KeyError Attempted to access a nonexistent key
KeyboardInterrupt Ctrl+C is pressed, and the keyboard terminates input
NameError Use undefined variables
SyntaxError Grammar mistakes
TypeError The type of the object passed does not match the required one
UnboundLocalError An attempt was made to access a local variable that has not yet been set
ValueError Passing in a value that the caller does not expect, even if the value is of the correct type
OSError Operating system execution error

For the most part, the built-in exceptions above will suffice, but sometimes you’ll need to customize some. Custom exceptions should inherit from the Exception class, either directly or indirectly, for example:

class MyExcept(Exception): def __init__(self, msg): self.message = msg def __str__(self): return self.message try: Raise MyExcept(' my exception! ') except MyExcept as ex: print(ex)Copy the code

Exception names all end in Error, and we need to follow this convention when naming our custom exceptions, just like standard exception names.