Toothpick Anemone
Toothpick Anemone

Reputation: 4644

How do we write an `except` statement which catches nothing?

I want a try-block such that any exception raised inside of thetry-block goes unhandled. This is so that I can write a try block in preparation for the future. Some day, I will write in some meaningful error handling. However, I don't have real except statements yet. The following sort of works, but is ugly

_ = type("", (Exception,), dict())

try:
    lizard = [1, 2, 3]
    y = z + w
    print(lizard[983])
except _:
    print("I hope this string never prints")

Upvotes: 3

Views: 1534

Answers (2)

chepner
chepner

Reputation: 531175

Skip the except clause altogether. A try statement needs at least one except clause or a finally clause, which executes whether or not you catch an exception.

try:
    lizard = [1, 2, 3]
    y = z + w
    print(lizard[983])
finally:
    pass

The finally clause won't actually execute any code, and does not affect the control flow of your code in any way; it just injects a no-op before you leave the try statement, whether by successfully completing the code or by raising an uncaught exception.

Once you start adding except clauses, you can either remove the finally clause or leave it in place.

(A deleted answer catches and immediately reraises any exception, which is also fine IMO:

try:
    ...
except Exception:
    raise

)

Upvotes: 5

basilisk
basilisk

Reputation: 1277

try:
   # do something
except:
   pass   # this will make nothing

the pass keyword is used for that purpose. when you want to make nothing, just write some code and come back later and think about what you really want to do there (or at least that's how I use it)

Upvotes: 0

Related Questions