If I have a code that raises more exceptions simultaniously like this
class A(Exception): pass
class B(Exception): pass
try:
try:
raise A('first')
finally:
raise B('second')
except X as c:
print(c)
Is there a way for handle all the exceptions toghether?
You can handle them all in this way:
except (A, B) as c:
Also you can define your own base class for your exceptions:
class BaseCustomException(Exception): pass
class A(BaseCustomException): pass
class B(BaseCustomException): pass
After it you can catch base exception, it will cover all derived exceptions:
except BaseCustomException as c:
When an new exception is thrown in a catch block or finally block that will propagate out of that block, then the current exception will be aborted (and forgotten) as the new exception is propagated outward. The new exception starts unwinding up the stack just like any other exception, aborting out of the current block (the catch or finally block) and subject to any applicable catch or finally blocks along the way.
check:Exception thrown in catch and finally clause
Related
I want to catch an exception, raise a custom exception, and then sys.exit(0) to exit the program gracefully.
I have tried the following:
In my main execution code, I have this:
try:
(some code)
except Exception as ex:
raise CustomException
and in CustomException class:
class CustomException(Exception):
def __init__(self):
sys.exit(0)
Unfortunately my custom exception is not getting raised this way and the main Exception is not getting caught.
I understand I could raise SystemExit but I need to generate a custom exception for me to catch in another code block down the road.
When I run this code:
i=0
while i<5:
i=i+1;
try:
SellSta=client.get_order(symbol=Symb,orderId=SellOrderNum,recvWindow=Delay)
except client.get_order as e:
print ("This is an error message!{}".format(i))
#End while
I got this error:
TypeError: catching classes that do not inherit from BaseException is not allowed
I read this tread Exception TypeError warning sometimes shown, sometimes not when using throw method of generator and this one Can't catch mocked exception because it doesn't inherit BaseException also read this https://medium.com/python-pandemonium/a-very-picky-except-in-python-d9b994bdf7f0
I kind of fix it with this code:
i=0
while i<5:
i=i+1;
try:
SellSta=client.get_order(symbol=Symb,orderId=SellOrderNum,recvWindow=Delay)
except:
print ("This is an error message!{}".format(i))
#End while
The result it's that ignores the error and go to the next while but I want to catch the error and print it.
I post the question in Spanish Stack with better results.
To translate and sum up:
The error occurs because in the exception clause you must indicate which exception you capture. An exception is a class that inherits (directly or indirectly) from the base class Exception.
Instead I have put client.get_order where python expected the name of the exception, and what you have put is a method of an object, and not a class that inherits from Exception.
The solution goes this way
try:
SellSta=client.get_order(symbol=Symb,orderId=SellOrderNum,recvWindow=Delay)
except Exception as e:
if e.code==-2013:
print ("Order does not exist.");
elif e.code==-2014:
print ("API-key format invalid.");
#End If
You'll need to code for every exception in here
What is a good way of raising sub-exceptions (is that's the term)?
Scenario:
I want to raise a custom ConnectivityException when http or ftp exception occurs. Is there any way to raise ConnectivityException such that exceptions are categorized properly (i.e. I should be able to tell if ConnectivityException is raised because of http ot ftp)?
A standard technique would be to subclass ConnectivityException to create exception classes specific to each kind of error condition:
class ConnectivityException(Exception): pass
class HTTPConnectivityException(ConnectivityException): pass
class FTPConnectivityException(ConnectivityException): pass
Then instead of raise ConnectivityException you can use raise HTTPConnectivityException or raise FTPConnectivityException, depending on which specific type of error you want to indicate.
Multiple exception blocks can be used to dispatch error handling according to the exception type:
try:
some_network_operation()
except HTTPConnectivityException as ex:
# This will execute if the error is an HTTPConnectivityException.
except FTPConnectivityException as ex:
# Likewise for FTPConnectivityException.
except ConnectivityException as ex:
# The generic case; this block will execute if the ConnectivityException isn't
# an instance of one of the earlier specified subclasses.
Note that the exception-handling blocks are tried in lexical order; the first block specifying a class to which the exception object belongs will be used. In this case, that means that you need to put the ConnectivityException block last, or else it will catch HTTPConnectivityException and FTPConnectivityException as well.
you can add an attribute named 'source' to ConnectivityException, and set it to 'http' or 'ftp' according to specific situation, when catch ConnectivityException, check the source attribute and decide what to do
here i recommend another way which uses inherit class
class ConnectivityException(Exception):
pass # you can define some attributes and methods, here I just escape
class HTTPConnectivityException(ConnectivityException):
pass
class FTPConnectivityException(ConnectivityException):
pass
def func():
if some_condition:
raise HTTPConnectivityException()
if some_other_condition:
raise FTPConnectivityException()
def another_func():
try:
func()
except HTTPConnectivityException as e:
pass # you can do something here
except FTPConnectivityException as e:
pass
In a code where there are different old-style classes like this one:
class customException: pass
and exceptions are raised this way:
raise customException()
Is there a type to catch all those old-style class exceptions? like this:
try:
...
except EXCEPTION_TYPE as e:
#do something with e
Or at least is there a way to catch everything (old- and new-style) and get the exception object in a variable?
try:
...
except:
#this catches everything but there is no exception variable
The only solution I can think of is using sys.exc_info
import sys
try:
raise customException()
except:
e = sys.exc_info()[1]
# handle exception "e" here...
my code is like below
class Something(models.Model)
def exception(self)
try:
Something.objects.all()
except Exception():
raise Exception()
called this method from testcases ,its working but i need to raise exception ,it does not catch the exception
and here is my test case
def test_exception(self):
instance = Something()
instance.exception()
its working fine but i need to raise exception from except block
This line:
except Exception():
should be:
except Exception:
def exception(self)
try:
Something.objects.all()
except Exception, err:
#print err.message (if you want)
raise err
This will catch the error and print the exact msg if required.
Why catch the Exception just to re-raise it?
If you are not doing anything in the except suite except re-raising the exception, then simply do not catch the exception in the first place:
#staticmethod
def exception():
Something.objects.all()
If you are doing something nontrivial inside the except suite, then:
def exception(self):
try:
Something.objects.all()
except Exception:
# do something (with self?)
raise
Then, to test that the exception method raises an Exception:
def test_exception(self):
instance = Something()
self.assertRaises(Exception, instance.exception)
This depends on Something.objects.all() raising Exception.
PS. If exception does not depend on self, then it is best to remove it from the argument list and make exception a staticmethod.
PPS. Exception is a very broad base exception class. A more specific exception would be more helpful for debugging, and allow other code to catch this specific exception instead of forcing it to handle any possible Exception.