Skip to content

Commit b657be1

Browse files
committed
Major cleanup in Exceptions
1 parent 29d03e0 commit b657be1

14 files changed

+32
-32
lines changed

photometry/BasePhotometry.py

+5-5
Original file line numberDiff line numberDiff line change
@@ -322,7 +322,7 @@ def __init__(self, starid, input_folder, output_folder, datasource='ffi',
322322
elif len(fname) == 0:
323323
raise FileNotFoundError("Target Pixel File not found")
324324
elif len(fname) > 1:
325-
raise OSError("Multiple Target Pixel Files found matching pattern")
325+
raise FileNotFoundError("Multiple Target Pixel Files found matching pattern")
326326

327327
# Open the FITS file:
328328
self.tpf = fits.open(fname, mode='readonly', memmap=True)
@@ -410,7 +410,7 @@ def __init__(self, starid, input_folder, output_folder, datasource='ffi',
410410
cursor.execute("SELECT ra,decl,ra_J2000,decl_J2000,pm_ra,pm_decl,tmag,teff FROM catalog WHERE starid={0:d};".format(self.starid))
411411
target = cursor.fetchone()
412412
if target is None:
413-
raise Exception("Star could not be found in catalog: {0:d}".format(self.starid))
413+
raise RuntimeError(f"Star could not be found in catalog: {self.starid:d}")
414414
self.target = dict(target) # Dictionary of all main target properties.
415415
cursor.execute("SELECT sector,reference_time,ticver FROM settings LIMIT 1;")
416416
target = cursor.fetchone()
@@ -1336,15 +1336,15 @@ def photometry(self, *args, **kwargs):
13361336

13371337
# Check that the status has been changed:
13381338
if self._status == STATUS.UNKNOWN:
1339-
raise Exception("STATUS was not set by do_photometry")
1339+
raise ValueError("STATUS was not set by do_photometry")
13401340

13411341
# Calculate performance metrics if status was not an error:
13421342
if self._status in (STATUS.OK, STATUS.WARNING):
13431343
# Simple check that entire lightcurve is not NaN:
13441344
if allnan(self.lightcurve['flux']):
1345-
raise Exception("Final lightcurve fluxes are all NaNs")
1345+
raise ValueError("Final lightcurve fluxes are all NaNs")
13461346
if allnan(self.lightcurve['flux_err']):
1347-
raise Exception("Final lightcurve errors are all NaNs")
1347+
raise ValueError("Final lightcurve errors are all NaNs")
13481348

13491349
# Pick out the part of the lightcurve that has a good quality
13501350
# and only use this subset to calculate the diagnostic metrics:

photometry/fixes/time_offset.py

+1-1
Original file line numberDiff line numberDiff line change
@@ -115,7 +115,7 @@ def time_offset(time, header, datatype='ffi', timepos='mid', return_flag=False):
115115
# files in earlier versions of the pipeline. In that case, we have to throw
116116
# an error and tell users to re-run prepare:
117117
elif datarel in (27, 29) and procver is None:
118-
raise Exception("""The timestamps of these data may need to be corrected,
118+
raise ValueError("""The timestamps of these data may need to be corrected,
119119
but the PROCVER header is not present. HDF5 files may need to be re-created.""")
120120

121121
elif datarel == 27 \

photometry/image_motion.py

+1-1
Original file line numberDiff line numberDiff line change
@@ -210,7 +210,7 @@ def calc_kernel(self, image, number_of_iterations=10000, termination_eps=1e-6):
210210

211211
# Check that reference image was actually given:
212212
if self.image_ref is None:
213-
raise Exception("Reference image not defined")
213+
raise RuntimeError("Reference image not defined")
214214

215215
# Define the motion model
216216
if self.warpmode == 'euclidian':

photometry/prepare.py

+2-2
Original file line numberDiff line numberDiff line change
@@ -211,7 +211,7 @@ def prepare_photometry(input_folder=None, sectors=None, cameras=None, ccds=None,
211211
cursor.execute("SELECT sector,reference_time FROM settings LIMIT 1;")
212212
row = cursor.fetchone()
213213
if row is None:
214-
raise OSError("Settings could not be loaded from catalog")
214+
raise RuntimeError("Settings could not be loaded from catalog")
215215
#sector = row['sector']
216216
sector_reference_time = row['reference_time']
217217
cursor.close()
@@ -395,7 +395,7 @@ def prepare_photometry(input_folder=None, sectors=None, cameras=None, ccds=None,
395395
offset = first_cadenceno - first_time/timedelt
396396
cadenceno[k] = np.round((time[k] - timecorr[k])/timedelt + offset)
397397
elif is_tess:
398-
raise Exception("Could not determine CADENCENO for TESS data")
398+
raise RuntimeError("Could not determine CADENCENO for TESS data")
399399
else:
400400
cadenceno[k] = k+1
401401

photometry/spice.py

+3-3
Original file line numberDiff line numberDiff line change
@@ -19,7 +19,7 @@
1919
from .utilities import download_parallel
2020

2121
#--------------------------------------------------------------------------------------------------
22-
class InadequateSpiceException(Exception):
22+
class InadequateSpiceError(Exception):
2323
pass
2424

2525
#--------------------------------------------------------------------------------------------------
@@ -431,7 +431,7 @@ def position(self, jd, of='TESS', relative_to='EARTH'):
431431
positions, _ = spiceypy.spkpos(of, times, 'J2000', 'NONE', relative_to)
432432
positions = np.atleast_2d(positions)
433433
except spiceypy.utils.exceptions.SpiceSPKINSUFFDATA:
434-
raise InadequateSpiceException("Inadequate SPICE kernels available")
434+
raise InadequateSpiceError("Inadequate SPICE kernels available")
435435

436436
return positions
437437

@@ -490,7 +490,7 @@ def position_velocity(self, jd, of='TESS', relative_to='EARTH'):
490490
pos_vel, _ = spiceypy.spkezr(of, times, 'J2000', 'NONE', relative_to)
491491
pos_vel = np.asarray(pos_vel)
492492
except spiceypy.utils.exceptions.SpiceSPKINSUFFDATA:
493-
raise InadequateSpiceException("Inadequate SPICE kernels available")
493+
raise InadequateSpiceError("Inadequate SPICE kernels available")
494494

495495
return pos_vel
496496

photometry/todolist.py

+1-1
Original file line numberDiff line numberDiff line change
@@ -150,7 +150,7 @@ def _ffi_todo(hdf5_file, exclude=[], faint_limit=15.0):
150150
cursor.execute("SELECT * FROM settings WHERE sector=? AND camera=? AND ccd=? LIMIT 1;", (sector, camera, ccd))
151151
settings = cursor.fetchone()
152152
if settings is None:
153-
raise Exception(f"Settings not found in catalog (SECTOR={sector:d}, CAMERA={camera:d}, CCD={ccd:d})")
153+
raise RuntimeError(f"Settings not found in catalog (SECTOR={sector:d}, CAMERA={camera:d}, CCD={ccd:d})")
154154

155155
# Find all the stars in the catalog brigher than a certain limit:
156156
cursor.execute("SELECT starid,tmag,ra,decl FROM catalog WHERE tmag < ? ORDER BY tmag;", [faint_limit])

photometry/utilities.py

+4-4
Original file line numberDiff line numberDiff line change
@@ -635,7 +635,7 @@ def download_file(url, destination, desc=None, timeout=60,
635635
pbar.update(len(block))
636636

637637
if os.path.getsize(destination) != total_size:
638-
raise Exception("File not downloaded correctly")
638+
raise RuntimeError("File not downloaded correctly")
639639

640640
except: # noqa: E722, pragma: no cover
641641
logger.exception("Could not download file")
@@ -693,7 +693,7 @@ def _wrapper(arg):
693693
errors.append(url[0])
694694

695695
if errors:
696-
raise Exception("Errors encountered during download of the following URLs:\n%s" % '\n'.join(errors))
696+
raise RuntimeError("Errors encountered during download of the following URLs:\n%s" % '\n'.join(errors))
697697

698698
#--------------------------------------------------------------------------------------------------
699699
class TqdmLoggingHandler(logging.Handler):
@@ -799,10 +799,10 @@ def sqlite_drop_column(conn, table, col):
799799
for sql in index_sql:
800800
m = regex_index.match(sql)
801801
if not m:
802-
raise Exception("COULD NOT UNDERSTAND SQL") # pragma: no cover
802+
raise RuntimeError("COULD NOT UNDERSTAND SQL") # pragma: no cover
803803
index_columns = [i.strip() for i in m.group(3).split(',')]
804804
if col in index_columns:
805-
raise Exception("Column is used in INDEX %s." % m.group(2))
805+
raise RuntimeError("Column is used in INDEX %s." % m.group(2))
806806

807807
# Store the current foreign_key setting:
808808
cursor.execute("PRAGMA foreign_keys;")

run_tessphot_mpi.py

+2-2
Original file line numberDiff line numberDiff line change
@@ -128,7 +128,7 @@ def main():
128128
else: # pragma: no cover
129129
# This should never happen, but just to
130130
# make sure we don't run into an infinite loop:
131-
raise Exception("Master received an unknown tag: '{0}'".format(tag))
131+
raise RuntimeError(f"Master received an unknown tag: '{tag}'")
132132

133133
tm.logger.info("Master finishing")
134134

@@ -186,7 +186,7 @@ def main():
186186
else: # pragma: no cover
187187
# This should never happen, but just to
188188
# make sure we don't run into an infinite loop:
189-
raise Exception("Worker received an unknown tag: '{0}'".format(tag))
189+
raise RuntimeError(f"Worker received an unknown tag: '{tag}'")
190190

191191
except: # noqa: E722, pragma: no cover
192192
logger.exception("Something failed in worker")

run_todo_merge.py

+3-3
Original file line numberDiff line numberDiff line change
@@ -73,7 +73,7 @@
7373
cursor.execute("SELECT COUNT(*) FROM original.todolist;")
7474
count_table2 = cursor.fetchone()[0]
7575
if count_table1 != count_table2:
76-
raise Exception("The two TODO-files are incompatible")
76+
raise RuntimeError("The two TODO-files are incompatible")
7777
# Columns that should be the same:
7878
cursor.execute("""SELECT COUNT(*) FROM main.todolist t1 LEFT JOIN original.todolist t2 ON t1.priority=t2.priority WHERE
7979
t2.priority IS NULL
@@ -84,7 +84,7 @@
8484
OR t1.cbv_area != t2.cbv_area
8585
;""")
8686
if cursor.fetchone()[0] != 0:
87-
raise Exception("The two TODO-files are incompatible")
87+
raise RuntimeError("The two TODO-files are incompatible")
8888

8989
# TODO: Create list of priorities where corrections should be re-run.
9090
# This is if the method has changed, or the status have changed:
@@ -128,7 +128,7 @@
128128
cursor.execute("DROP TABLE %s;" % tbl)
129129
conn.commit()
130130
else:
131-
raise Exception("bla bla bla: %s" % tbl)
131+
raise RuntimeError("bla bla bla: %s" % tbl)
132132

133133
# Using temporary directory to dump the needed tables
134134
# to raw SQL file and insert them into the combined SQLite file afterwards:

tests/test_basephotometry.py

+1-1
Original file line numberDiff line numberDiff line change
@@ -50,7 +50,7 @@ def test_basephotometry_invalid_input(SHARED_INPUT_DIR):
5050
assert str(e.value) == "SECTOR, CAMERA and CCD keywords must be provided for FFI targets."
5151

5252
# Test target not in the catalog:
53-
with pytest.raises(Exception) as e:
53+
with pytest.raises(RuntimeError) as e:
5454
with BasePhotometry(0, SHARED_INPUT_DIR, OUTPUT_DIR, datasource='ffi', **DUMMY_KWARG):
5555
pass
5656
assert str(e.value) == "Star could not be found in catalog: 0"

tests/test_fixes.py

+2-2
Original file line numberDiff line numberDiff line change
@@ -37,11 +37,11 @@ def test_fixes_time_offset_invalid_input():
3737

3838
# The cases of data release 27 and 29 and no PROCVER:
3939
hdr = {'DATA_REL': 27, 'CAMERA': 1, 'PROCVER': None}
40-
with pytest.raises(Exception):
40+
with pytest.raises(ValueError):
4141
fixes.time_offset(time, hdr)
4242

4343
hdr = {'DATA_REL': 29, 'CAMERA': 2, 'PROCVER': None}
44-
with pytest.raises(Exception):
44+
with pytest.raises(ValueError):
4545
fixes.time_offset(time, hdr)
4646

4747
#--------------------------------------------------------------------------------------------------

tests/test_imagemotion.py

+1-1
Original file line numberDiff line numberDiff line change
@@ -39,7 +39,7 @@ def test_imagemotion(SHARED_INPUT_DIR, warpmode):
3939
assert len(imk) == 0, "Kernel should be an empty array for 'unchanged'"
4040
else:
4141
# Trying to calculate kernel with no reference image should give error:
42-
with pytest.raises(Exception) as e:
42+
with pytest.raises(RuntimeError) as e:
4343
ImageMovementKernel(image_ref=None, warpmode=warpmode).calc_kernel(img)
4444
assert str(e.value) == "Reference image not defined"
4545

tests/test_spice.py

+4-4
Original file line numberDiff line numberDiff line change
@@ -15,7 +15,7 @@
1515
from tempfile import TemporaryDirectory
1616
import conftest # noqa: F401
1717
from photometry import AperturePhotometry
18-
from photometry.spice import TESS_SPICE, InadequateSpiceException
18+
from photometry.spice import TESS_SPICE, InadequateSpiceError
1919
from photometry.utilities import find_tpf_files, find_hdf5_files, add_proper_motion
2020
from photometry.plots import plt, plots_interactive
2121
from mpl_toolkits.mplot3d import Axes3D # noqa: F401
@@ -64,15 +64,15 @@ def test_position_velocity():
6464
# We should fail with a timestamp that are outside the TESS SPICE coverage:
6565
# The timestamp used here is well before TESS was launched
6666
time_nocoverage = 1000 + 2457000
67-
with pytest.raises(InadequateSpiceException) as e:
67+
with pytest.raises(InadequateSpiceError) as e:
6868
knl.position(time_nocoverage)
6969
assert str(e.value) == 'Inadequate SPICE kernels available'
7070

71-
with pytest.raises(InadequateSpiceException) as e:
71+
with pytest.raises(InadequateSpiceError) as e:
7272
knl.velocity(time_nocoverage)
7373
assert str(e.value) == 'Inadequate SPICE kernels available'
7474

75-
with pytest.raises(InadequateSpiceException) as e:
75+
with pytest.raises(InadequateSpiceError) as e:
7676
knl.position_velocity(time_nocoverage)
7777
assert str(e.value) == 'Inadequate SPICE kernels available'
7878

tests/test_utilities.py

+2-2
Original file line numberDiff line numberDiff line change
@@ -438,10 +438,10 @@ def test_sqlite_drop_column(factory, foreign_keys):
438438

439439
# Attempting to drop a column associated with an index should
440440
# cause an Exception:
441-
with pytest.raises(Exception):
441+
with pytest.raises(RuntimeError):
442442
u.sqlite_drop_column(conn, 'tbl', 'col_c')
443443

444-
with pytest.raises(Exception):
444+
with pytest.raises(RuntimeError):
445445
u.sqlite_drop_column(conn, 'tbl', 'col_e')
446446

447447
#--------------------------------------------------------------------------------------------------

0 commit comments

Comments
 (0)