Exception handling: try/except
The operation of index lookup will result in an error when the index is searched beyond the bounds. For example:
>>> s="long" >>> s[4] Traceback (most recent call last): File "<stdin>", line 1, in <module> IndexError: string index out of range
The error reported is IndexError. If you put index lookup in a function:
def fetcher(obj,index): return obj[index]
When the function is called, if the index inside the function is out of bounds, the exception will be reported to the function caller.
>>> fetcher(s,3) 'g' >>> fetcher(s,4) Traceback (most recent call last): File "<stdin>", line 1, in <module> File "<stdin>", line 2, in fetcher IndexError: string index out of range
You can use try/except to catch exceptions.
try: statement1 ... statementN except <ERRORTYPE>: ...statementS...
For example, in a try, statements are monitored for correct execution, and ERRORTYPE is the type of error to monitor.
- As long as any statement in the try throws an error, the statement following the exception statement in the try will no longer execute.
- If the error thrown happens to be the type of error monitored by except, the statement in the statementS section is executed;
- If an exception happens to be caught (matched) by except, the program will continue executing after executing statementS, and if it is not caught, the program will terminate.
- In other words, when except catches an error, it handles it, and the program does not stop because it has already handled the error
def fetcher(obj, index): return obj[index] s = "long" try: print(fetcher(s, 3) * 4) print(fetcher(s, 4) * 4) except IndexError: print("something wrong") print("after Exception, Continue")
The fetcher(s, 4) above throws an exception and matches exactly the exception type monitored by except, so output something wrong, after the exception is handled, the program continues to execute, that is, print() after try/except.
Exception handling: try/finally
finally is a statement paragraph that must be executed after try. Can be used in conjunction with except.
try: statement1 ... statementN except <ERRORTYPE>: ...statementS... finally: ...statementF...
finally executes regardless of whether the statement in the try has an exception or whether except has caught the corresponding exception:
- If the exception is not caught, the program exits after finally execution
- If an exception is caught by except, the final statement is executed after the except statement is executed, and the program continues to run
In general, finally is used to clean up the program afterwards.
def fetcher(obj, index): return obj[index] s = "long" try: print(fetcher(s, 3) * 4) print(fetcher(s, 4) * 4) except IndexError: print("something wrong") finally: print("in finally") print("after Exception, Continue")
Exception generated: raise and assert
* Use raise or assert to actively generate exceptions. Raise can throw an exception directly, assert needs to be judged by a Boolean value, and then throw the given error.
raise is used to manually trigger an exception. Each exception is an exception class, so triggering is actually an instance object that triggers an exception class.
The as keyword assigns except-captured exception objects to the data variable
except Exception as e: print(e)
For example, make a useless judgment in a function to demonstrate raise:
def fetcher(obj, index): if index >= len(obj): raise IndexError return obj[index]
This is the same as direct index crossing. The exception IndexError thrown by raise above is a built-in exception, and once an exception is thrown, you can handle it as described earlier.
Many times, programs are debugged directly in assert using the Boolean values of False and True.
assert True, "assert not hit" assert False, "assert hit"
Custom Exception
Exceptions in python are defined by classes, and all exception classes inherit from Exception classes, while Exception inherits from BaseException (which cannot be directly the parent of other exception classes). So when customizing exceptions, you should also inherit Exception, of course, an intermediate exception class can also be inherited.
When customizing exception classes, you can override the construction method_u init_u (), so that when raise exceptions occur, you can specify the constructed data. Further, you can override u str_u From custom exception output.
class MyError(Exception): def __init__(self,line,file): self.line = line self.file = file def __str__(self): return "format failed: %s at %s" % (self.file, self.line) def format(): ... raise MyError(42, "a.json") ... try: format() except MyError as E: print(E)