Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
168 views
in Technique[技术] by (71.8m points)

How to ignore one particular exception in Python?

I have a try block case in my code and I want to ignore one particular exception and all the rest should be raised.

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?

question from:https://stackoverflow.com/questions/65841806/how-to-ignore-one-particular-exception-in-python

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...