user797963
user797963

Reputation: 3027

python - how to reduce repetitive try/catch blocks?

I'm new to python and am writing a CLI wrapper for an internal tool using a python wrapper to a C++ API, and find myself constantly defining functions with identical try/catch blocks inside of them, with the only difference being the single call to the API.

For example...

px5 = PX5()

try:
  px5.connect()
except PX5Exception:
  for te in px5.errors:
    print(te)

def some_action(some_val):
  try:
    px5.run_method(some_val)
  except PX5Exception:
    for te in px5.errors:
      print(te)
    exit()

def some_other_action(some_val):
  try:
    return px5.run_some_other_method(some_val)
  except PX5Exception:
    for te in px5.errors:
      print(te) 
    exit()

Am I just way overdoing it with the try/catch blocks? Each individual command I need to run can easily have exceptions that I want to catch and display in a friendly manner vs. displaying the entire exception (basically, as the tool itself would display them if you weren't going through the API and using the CLI directly).

Upvotes: 2

Views: 172

Answers (1)

Amber
Amber

Reputation: 526583

One option would be to make a wrapper method:

def print_errors(func, *args, **kwargs):
    try:
        return func(*args, **kwargs)
    except PX5Exception:
        for te in px5.errors:
            print(te)

Then instead of a try/except block each time, you'd just wrap:

print_errors(px5.run_some_other_method, some_val)

Upvotes: 2

Related Questions