Try and Except, how?

Hello,

I try :slight_smile: to get fit in using Try statement. the Exercise is very basic i think:
https://docs.python.org/3/tutorial/errors.html


I have 2 ways to get to my Object.Type: So i want to kick out everything thats not a double



OUT = []


for i in IN[0]:
    if not type(i) is Double:
        OUT.append(i)
    else:
        OUT.append(0)

second example (also does not work)


values = IN[0]
OUT = []

def fail():
    1 / 0

OUT = []
for i in values:
    try:
        fail(values)
    except:
        OUT.append(i)

    OUT.append(0.0)

I think the topic is not focused on the zero issue. I would like to know some practical examples of the Try and Except statement.

GroupByFunction does work: Who do i manage it in Python?

Decimal numbers are called “float” in Python, not double.

1 Like

Have you checked your errors? Your code is written for a single list yet you’re supplying a list of sublists.

I use Try/Except for two things. 1) Catching specific conditions to return a warning and 2) “lazy” filtering or handling of expected problems.

One example would be the difference between parameters that represent a string and parameters that represent an object but read as a string. I could write something like:

try:
   val = element.Parameter.AsString()
except:
   val = element.Parameter.AsValueString()

This lets me attempt to get the value using AsString() but if that method doesn’t exist, rather than just erroring, the code will continue with what’s in the exception loop and us AsValueString().

EDIT: I forgot a very important third reason for Try/Except loops: troubleshooting. You can add a Try loop to determine where exactly you might be hitting exceptions and essentially “skip” parts of code that may be problematic.

3 Likes

Try statements should NEVER be used for flow control;

Try: 
   ThingToDo
Except:
   OtherThingToDo

Is extremely slow in terms of processing; an If statement will be more functional speed wise. @Thomas_Mahon has an excellent post on the subject.

The best use of Try I know of is in error handling as @Nick_Boyts indicated. That code is more like this:

Try:
   ThingToAttempt
Except:
   ErrorMessageInsteadOfResult

I talked briefly about this in the last community conversation, at around the 50 minute mark of this video: 29 - Dynamo and Civil 3D's API - YouTube

6 Likes

To add to Jacob’s point on flow control, try/except is super handy when you’re expecting something to sometimes fail (e.g. a user gets the matching name of a view wrong). Best practice is to specify the error if possible so you can catch the error(s) as intended though. They’re a bit of a necessary evil given Dynamo typically wont get through nulls in most cases, usually I use them to yield ‘None’ in a value list, and often will make a ‘did it work’ output as well (made of booleans, so it can be used as a mask on the original data to allow it to proceed on in a filtered state) so they will generate an error technically, but handle the step that will cause that and proceed onward.

Iirc, the syntax for catching specific errors is:

try:
	#a thing
except ErrorType as error:
	#catch the error

Give I’ve been scolded by programming chums for using them in the past, I believe the principle is they are a brute force/last resort type statement if optimisation is a goal in your code. A good example of avoiding a try/except is the check for whether a view is placed as a viewport when trying to place views on sheets versus running it through a try/except. The boolean outcome can be used to drive an if/else pathway where the else just bypasses the already placed view.

1 Like

To grasp these concepts, I suggest you take a structured Python course.
See the one I took below offered on edx. It’s a two-week course that runs through the basics of the Python language. To get more in-depth there is a follow-up course on data structures which I also recommend.
Cheers.

1 Like

@bayowindapo I start reading the Nature of Code :slight_smile:

3 Likes

Looks like a great book thanks for sharing.

1 Like