I've heard recently about the possibility of handling exceptions in python using the statement
try:
and
except WhateverError:
I was just wondering if it is a good idea to use it when defining the next class. It is supposed to represent a terrain. Each number of the matrix represents a coordinate of it and the number is the height of that coordinate.
class base_terreny(object):
# create default mxn terrain #
def __init__(self, rows, columns):
self.rows=rows
self.columns=columns
self.terrain=[[0]*columns for _ in range(rows)]
def __getitem__(self, pos): #return height of coordinate
try:
return self.terrain[pos[1]][pos[0]]
except (IndexError,TypeError):
return 0
def __setitem__(self, pos, h): #set height
try:
self.terrain[pos[1]][pos[0]]=h
except (IndexError,TypeError):
return None
Or would it be better to do it like:
if pos[0]<=self.columns and pos[1]<=self.rows:
self.terrain[pos[1]][pos[0]]=h
except (IndexError, TypeError):.