In Python, exceptions serve as a means of signalling errors or exceptional conditions during program execution. To manually raise an exception, the raise statement is utilized.
To raise an exception, employ the constructor for the specific Exception class that best describes your issue. For instance:
raise ValueError('A very specific bad thing happened.')
This allows you to provide a customized error message that makes it easier to identify the culprit.
Refrain from raising generic Exceptions like Exception. These become difficult to catch as you'll have to catch all subclassed, more specific exceptions as well.
Use the raise statement with the most specific Exception constructor that fits your situation. You can also pass arguments to the constructor:
raise ValueError('A very specific bad thing happened', 'foo', 'bar', 'baz')
These arguments can be retrieved using the args attribute of the Exception object.
When handling exceptions, you may want to log specific errors and re-raise them. Preserve the stack trace by using a bare raise statement:
logger = logging.getLogger(__name__) try: do_something_in_app_that_breaks_easily() except AppError as error: logger.error(error) raise # just this! # raise AppError # Don't do this, you'll lose the stack trace!
While it's possible to modify errors using sys.exc_info(), prefer a bare raise for preserving the stack trace. This can be particularly problematic when using threading, as you may capture the wrong traceback.
In Python 3, you can chain exceptions to preserve tracebacks:
raise RuntimeError('specific message') from error
Avoid the following as they can silently catch and hide errors or even silently raise the wrong exception:
raise ValueError, 'message' # Deprecated raise 'message' # Seriously wrong, don't do this
An example of raising an exception for incorrect API usage:
def api_func(foo): '''foo should be either 'baz' or 'bar'. returns something very useful.''' if foo not in _ALLOWED_ARGS: raise ValueError('{foo} wrong, use "baz" or "bar"'.format(foo=repr(foo)))
You can define custom error types to indicate specific application-related errors:
class MyAppLookupError(LookupError): '''raise this when there's a lookup error for my app'''
The above is the detailed content of How Do I Effectively Raise Exceptions in Python?. For more information, please follow other related articles on the PHP Chinese website!