1

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
3
  • 2
    See Python Forgiveness vs. Permission and Duck Typing Commented Apr 24, 2013 at 20:29
  • Your syntax is incorrect; to catch multiple exceptions, specify them as a tuple: except (IndexError, TypeError):. Commented Apr 24, 2013 at 20:30
  • 1
    In this case, go with the exception handler; going out of bounds is going to be the exception. Commented Apr 24, 2013 at 20:31

1 Answer 1

3

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.