Question

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
Was it helpful?

Solution

Both ways are acceptable, however it is probably cleaner to use the second one. While exceptions are often useful, what you are actually trying to test using the exception is the second technique. While it really doesn't matter in this case, it is generally regarded as better to use the if statement unless you are actually trying to handle an error differently. In a different circumstance, there could be other things than what you would be testing for that may trigger the error.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top