python customizes methods for exceptions and exception capture

  • 2020-12-22 17:43:41
  • OfStack

Exception capture:


try: 
 XXXXX1
 raise Exception( " xxxxx2 " ) 
except  ( Exception1 . Exception2 ,...) : 
 xxxx3
else:
 xxxxx4
finally:
 xxxxxxx5

1. The raise statement can be customized with error message, as above.

2. The statement after raise will not be executed because the exception has been thrown and the control flow will jump to the exception capture module.

3. The except statement can be followed by one except with multiple exceptions, or multiple statements can be used to catch multiple exceptions and handle them differently.

except statement catches an exception that does not occur, then statement blocks in except are not executed. Instead, execute the statement in else

5. In the above statement try/except/else/finally's order must be try � > except X � > except � > else � > finally, i.e. all except must precede else and finally, else (if any) must precede finally, and except X must precede except. Otherwise, a syntax error will occur.

6. Both else and finally are optional.

7. In the complete statement above, the existence of the else statement must be based on the except X or except statement. Using the else statement in try block without the except statement will cause a syntax error.

Output of abnormal parameters:


try:
 testRaise()
except PreconditionsException as e: #python3 "Must be used as
 print (e)

To customize the exception, you simply need to customize the exception class to inherit from the parent class Exception. In the custom exception class, override the parent init method.


class DatabaseException(Exception):
 def __init__(self,err=' Database error '):
  Exception.__init__(self,err)

class PreconditionsException(DatabaseException):
 def __init__(self,err='PreconditionsErr'):
  DatabaseException.__init__(self,err)

def testRaise():
 raise PreconditionsException()

try:
 testRaise()
except PreconditionsException as e:
 print (e)

Note: PreconditonsException is also a subclass of DatabaseException.

So if raise PreconditionException, you can catch it with both exception classes.

However, if it is raise DatabaseException, you cannot catch it with PreconditonsException.


Related articles: