I wrote a library that sometimes raises exceptions. There is an exception that I want to deprecate, and I would like to advise people to stop catching them, and provide advises in the warning message. But how to make an exception emit a DeprecationWarning
when catched?
import warnings
class MyException(ValueError):
...
warnings.warn(
"MyException is deprecated and will soon be replaced by `ValueError`.",
DeprecationWarning,
stacklevel=2,
)
...
def something():
raise MyException()
try:
mylib.something()
except MyException: # <-- raise a DeprecationWarning here
pass
How can I modify MyException
to achieve this?
Catching Exceptions in Python In Python, exceptions can be handled using a try statement. The critical operation which can raise an exception is placed inside the try clause. The code that handles the exceptions is written in the except clause.
I use the following simple function to check if the user passed a non-zero number to it. If so, the program should warn them, but continue as per normal. It should work like the code below, but should use class Warning() , Error() or Exception() instead of printing the warning out manually.
The warn() function defined in the ' warning ' module is used to show warning messages. The warning module is actually a subclass of Exception which is a built-in class in Python. print ( 'Geeks !' )
You can't. None of the logic that occurs in except MyException
is customizable. Particularly, it completely ignores things like __instancecheck__
or __subclasscheck__
, so you can't hook into the process of determining whether an exception matches an exception class.
The closest you can get is having the warning happen when a user tries to access your exception class with from yourmodule import MyException
or yourmodule.MyException
. You can do that with a module __getattr__
:
class MyException(ValueError):
...
# access _MyException instead of MyException to avoid warning
# useful if other submodules of a package need to use this exception
# also use _MyException within this file - module __getattr__ won't apply.
_MyException = MyException
del MyException
def __getattr__(name):
if name == 'MyException':
# issue warning
return _MyException
raise AttributeError
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