# I've tried both of these: try: for part in parts: dirs = [dir for dir in os.listdir(path_to_check) if not isfile(os.path.join(path_to_check, dir))] if "thing" in dirs: return path_to_check del path_parts[-1] else: raise ValueError("thing not found") except ValueError as e: print(e.value()) ############################# for part in parts: dirs = [dir for dir in os.listdir(path_to_check) if not isfile(os.path.join(path_to_check, dir))] if "thing" in dirs: return path_to_check del path_parts[-1] else: raise ValueError("thing not found") # test with self.assertRaises(ValueError): self.stupid_function()