The typical structure for exception handling is below:
try:
pass
except Exception, e:
raise
else:
pass
finally:
pass
May I know what does except Exception, e:
orexcept Exception as e:
mean?
Typically I will use print (e)
to print the error message but I am wondering what the program has done to generate the e.
If I were to construct it in another way (below), how would it be like?
except Exception:
e = Exception.something
What should the method be to replace the something
?
When the body of code under try
gives no exception, the program will execute the code under else
. But, what does finally
do here?
User-Defined Exceptions This is useful when you need to display more specific information when an exception is caught. In the try block, the user-defined exception is raised and caught in the except block. The variable e is used to create an instance of the class Networkerror.
except is used to catch and handle the exception(s) that are encountered in the try clause. else lets you code sections that should run only when no exceptions are encountered in the try clause.
In contrast, the except Exception as e statement is a statement that defines an argument to the except statement. e in the latter statement is utilized to create an instance of the given Exception in the code and makes all of the attributes of the given Exception object accessible to the user.
Ignoring a specific exception by using pass in the except block is totally fine in Python. Using bare excepts (without specifying an exception type) however is not. Don't do it, unless it's for debugging or if you actually handle those exceptions in some way (logging, filtering and re-raising some of them, ...).
except Exception as e
, or except Exception, e
(Python 2.x only) means that it catches exceptions of type Exception
, and in the except:
block, the exception that was raised (the actual object, not the exception class) is bound to the variable e
.
As for finally
, it's a block that always gets executed, regardless of what happens, after the except
block (if an exception is raised) but always before anything else that would jump out of the scope is triggered (e.g. return
, continue
or raise
).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With