A brief introduction to exception handling in Python
- 2020-05-09 18:46:19
- OfStack
The python exception handling mechanism is similar to java in that it adopts the structure of try-except-finally.
try-except detects exceptions
format
try:
try_statement
except (ErrorType1, ErrorType2),e:
handle_statement
finally:
finally_statement
The instance
#!/usr/bin/python
try:
a=12
b=0
c = a/b
except Exception, e:
print "Exception occurs: " , e
finally:
print "finally handle!"
Context manager (with... as... Statement)
The with statement is particularly useful in scenarios where the resource is opened first and then released, because it automatically releases the occupied resource without the need to explicitly release the resource
format
with context_expr [as var]:
with_statement
raise throws an exception
format
raise Exception[, args] or raise Exception(args)
The instance
raise Exception( ' exampleException')
assertions
Detect key points in the program, triggering AssertError(assertion error) if the assertion is unsuccessful
Format is as follows
assert expression[, arguements]