0

I have defined a class to contain a grid of points. I want to perform error checking on the keyword argument Grid_Points to make sure the user gives either a float or int for the number of points. I want there to be an error if they don't specify anything.

class MyGrid:
    def __init__(self, Grid_Points=None, L=0.0, R=1.0):
    Grid = np.linspace(start=L, stop=R,num=Grid_Points, retstep=True)
    self.Grid = Grid[0]
    self.dx = Grid[1]

I implemented the following try and except clauses. When I do TestGrid = MyGrid() I get an error that says UnboundLocalError: local variable 'Grid' referenced before assignment.

What am I missing? I thought trying to do linspace within the try clause would result in an exception (because Grid_Points will be equal to None) and so it should go to the except clause and print out the statement I specified and then terminate execution of the code. I purposely chose to use Exception so it would catch anything (I'll use something more specific once I get this working at all). But the code appears to be getting past the try and except blocks.

class MyGrid:
    def __init__(self, Grid_Points=None, L=0.0, R=1.0):
    try:
        Grid = np.linspace(start=L, stop=R,num=Grid_Points, retstep=True)
    except Exception:
        print('Enter the number of grid points as either a float or int')
    self.Grid = Grid[0]
    self.dx = Grid[1]
Nukesub
  • 191
  • 5

1 Answers1

1

You say that you expect your code to print and terminate -- but you forgot to terminate the code. You handled the exception, so your execution proceeds directly to the rest of the code:

self.Grid = Grid[0]
self.dx = Grid[1]

Since Grid is undefined (the linspace call aborted), the code now faults and dies here. You need a conditional clause of some sort to handle the case, such as moving the self assignments into your try block:

class MyGrid:
    def __init__(self, Grid_Points=None, L=0.0, R=1.0):
      try:
        Grid = np.linspace(start=L, stop=R,num=Grid_Points, retstep=True)
        self.Grid = Grid[0]
        self.dx = Grid[1]
      except Exception:
        print('Enter the number of grid points as either a float or int')

Better yet, don't terminate: simply loop until you get a valid response.

Prune
  • 76,765
  • 14
  • 60
  • 81
  • thank you for the helpful response. I thought if the code made it into the `except` block it would terminate. Since an exception is raised in the `try` block by the `linspace` (because of `None`, right?) shouldn't the code have gone to the `except` block where it terminates after `print` statement? – Nukesub Jul 01 '21 at 00:05
  • No -- refer to any tutorial on `try -- except`. You went out of your way to tell the Python run-time system, "Don't worry about that exception: I can handle it!" You overrode the default exception handler -- anything you want to happen at this point, you now have to explicitly code. – Prune Jul 01 '21 at 15:34