Import Revit Exceptions Inquiry

I am in infant stages of a script. Below is a working piece of it, for device selection in Revit. But I wanted to make sure my manner of importing the OperationCanceledException is correct.

Is the manner in which I have done that correct? Or is there a cleaner way to perform the same goal? Yes, ChatGPT helped me. I am learning, slowly.

from pyrevit import revit, DB, forms
from Autodesk.Revit.UI.Selection import ObjectType
import Autodesk.Revit.Exceptions.OperationCanceledException

selected_elements = [ ]

# Prompt the user to select elements individually
while True:
        selection = revit.uidoc.Selection
        selected_object = selection.PickObject(ObjectType.Element,\
            "Select Fire Alarm Device (Press Esc to finish selection)")
        if selected_object:
            element = revit.doc.GetElement(selected_object.ElementId)
            # Check if the selected element is of the allowable family name
            if element.Symbol.FamilyName == "Allowed Fam Name":
                forms.alert("Please select an element of the 'Allowed Fam Name' family.")
    except Autodesk.Revit.Exceptions.OperationCanceledException:
        # User canceled the selection, exit the loop


This is better (written while eating my breakfast without chatgpt :nerd_face:)

From Autodesk.Revit.Exceptions import OperationCanceledException


except OperationCanceledException:

Thank you! I see my error now. This is how we learn!!

1 Like

Hi @toothbrush,
Yours was not an “error” per se, but another way to do the same thing, importing objects from other modules/libraries.

Another way to do this, especially if you have many things to import from the same module, is using an alias:

import Autodesk.Revit.Exceptions as exc
except exc.OperationCanceledException:

This will keep the code short and lets you access all the revit exceptions.

You will also see something like from module import *; DON’T DO THAT! While it does the same thing and allows you to skip the alias, it is a python bad practice that can result in unpredictable errors.

1 Like