
In python, every built-in exception must be an instance of a class which inherits from BaseException. But user-defined exception class should inherit from Exception or its subclass. Exception is an subclass of BaseException.
Please note: “When an exception has been assigned using as target, it is cleared at the end of the except clause.”
Here I would like to illustrate several methods for handling exceptions.
raise allows you to force generate your own customized exceptions, which makes you control your code more convenient and effective. Although you still can raise built-in exceptions.
Run the expression on terminal:
raise Exception('spam', 'eggs') |
And you can just use raise like this:
import sys |
According to the officail document, “If no expressions are present, raise re-raises the last exception that was active in the current scope. If no exception is active in the current scope, a RuntimeError exception is raised indicating that this is an error.”
Then, you can set your own traceback by using with_traceback() exception method, such as:
raise Exception("something wrong with trace").with_traceback(tracebackobj) |
You can also use from clause in raise statement to rasie nested exceptions from the clause expression.Exception chaining can be explicitly suppressed by specifying None in the from clause:
try: |
try statement
try statement can has except clause, or finally clause, or both. raise can be used in try expression.
except clause
One example including the usage of instance.args:
try: |
Just as the document says, “If an exception has arguments, they are printed as the last part (‘detail’) of the message for unhandled exceptions.”
finally clause
“A finally clause is always executed before leaving the try statement, whether an exception has occurred or not.” “The finally clause is also executed “on the way out” when any other clause of the try statement is left via a break, continue or return statement.”
For example, with/without return, the finally will be executed:
def divide(x, y): |
User-defined Exceptions
You can design your own exception classes inherited from Exception and its subclasses, and you’d better name your class end with “Error”.
PS:
Using following code, you don’t need to close the file by call f.close(), the with statement helps you do that.
with open(“myfile.txt”) as f:
for line in f:
print(line, end=””)




近期评论