简体   繁体   中英

Python - Raising an exception or not?

Here's a description of my problem:

I have the task to take a bunch of tablenames and put a prefix in front of them, like so:

PREFIX = 'foo_';

prefixed_tablename = "".join([PREFIX, tablename[:27]])

(The tablename must never exceed 30 characters (some Oracle DB restriction), this is why I only take the first 27 chars).

Now, sometimes this can lead to duplicate tablenames (if only the last 3 chars of a tablename differ).

I could implement some fancy algorithm for creating unique tablenames but at the moment detecting duplicate names would be sufficient. So I thought about storing them in a set, and if creating a prefixed tablename, check the set to see if such a tablename already exists.

Now, for the real problem:

If a duplicate gets detected, I need to stop my script executing, showing some kind of error. In Java, I would just raise an exception, but I don't know if this would be the preferred way in Python.

Should I raise an exception, or just print out a message and exit?

27 + 4 = 31.

Why wouldn't you use an exception? If you later don't want to just exit, but instead catch the exception and do something with it at an outer scope, you've got less to change than if you use sys.exit .

Exceptions in Python are actually used somewhat more liberally than in Java (for example, iterators use them internally to signal when iteration is to stop). If this is really an "Exceptional" situation -- that is, if this won't be happening often, as a matter of course -- then this is a perfect situation for which to raise an exception.

I would say you should raise an exception. If you construct the exception with the message then the script will exit with the message as you want, and if you ever want to change how you handle the error it might be easier if you raise an exception. Also, if you ever use this code as part of a larger program, you would be able to decide how to handle the error separately in the larger program.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM