I have a try block case in my code and I want to ignore one particular exception and all the rest should be raised.
try
For example:
try: blah except <exception> as e: raise Exception(e)
In this kind of case, I want all the exceptions to be raised except for one case, say if the exception is "query not found" I have to ignore it.
How do I ignore that single exception?
I can use multiple except blocks but how to define a exception?
You can give something like this:
try: print(x) except NameError: print("Variable x is not defined") except: print("Something else went wrong")
In this case, you want to catch NameError and specify a message. For all others, you want to specify another message.
Let's say you want to ignore NameError, then you can just give continue or pass.
continue
pass
Alternatively, you can also raise an exception.
Example will be:
x = -1 if x < 0: raise Exception("Sorry, no numbers below zero")
So you can use a combination of all this to get you what you want.
If you want more details on exception, see the below links:
https://docs.python.org/3/tutorial/errors.html
https://www.w3schools.com/python/python_try_except.asp
https://realpython.com/python-exceptions/
And on stack overflow (as Gino highlighted), see Handling all but one exception
1.4m articles
1.4m replys
5 comments
56.9k users