using finally clause vs without using finally clause

40 Views Asked by At

What is the difference between this code that uses a finally statement and the code without a finally statement?

# code 1
a = 10
b = 0

try:
    c = a / b
    print(c)
except ZeroDivisionError as error:
    print(error)
finally:
    print('Finishing up.')

and this for code without finally statement, they are looks same. Is there difference such as performance or what?

# code 2
a = 10
b = 0

try:
    c = a / b
    print(c)
except ZeroDivisionError as error:
    print(error)
print('Finishing up.') # without using finally statement.

Here is flowchart I got from that site try-except-finally

In my real case or real application, I'm using OpenCV in frame loop to handle error, but I have no idea shall I use finally or without using finally?

  while ret:
    try:
      # Write the preview frame to the video file
      video_writer_preview.write(frame)

      log_dict[pid] = f'Frame {view_class_dict[pid]} inferencing... '
      # Inference
      # frame = inference_detect_mtcnn(frame)
      if is_dopler:
        frame = inference_detect_yoloDopler(frame)
      else:
        if is_abnclass:
          if view_class_dict[pid] == '4CH':
            frame = inference_detect_yolo4CH(frame)
          elif view_class_dict[pid] == '5CH':
            frame = inference_detect_yolo5CH(frame)
          elif view_class_dict[pid] == 'LA':
            frame = inference_detect_yoloLA(frame)
          elif view_class_dict[pid] == 'SA':
            frame = inference_detect_yoloSA(frame)
          elif view_class_dict[pid] == 'SUB':
            frame = inference_detect_yoloSUB(frame)

      # Write the processed frame to the video file
      video_writer_processed.write(frame)

    except Exception as e:
      log_dict[pid] = f'Frame inference error! {e}'
      print(f"error: {e}")
    finally: # shall I use finally clause?
      # Read the next frame
      ret, frame = capture.read()
      progress_dict[pid] += 1
0

There are 0 best solutions below