8

I have try-except block in python, and I want to do nothing when exception occurs. My code is as follows:

for i in range(len(grid)):
    for j in range(len(grid[i])):
        try:
            count = count > int(grid[i][j]) ? count : int(grid[i][j])
        except:
            //Do nothing here

How do I do nothing when exception is caught.

Thanks.

Peter Svensson
  • 6,105
  • 1
  • 31
  • 31
hrishikeshp19
  • 8,838
  • 26
  • 78
  • 141
  • 12
    Please do not use `try: .. except: pass` - at least specify an exception type which you want to ignore! Otherwise you are likely to get hard-to-debug problems at some point when you don't notice an exception being raised. – ThiefMaster Feb 11 '12 at 20:24
  • 3
    If you are going to do this, I *strongly* recommend that you specify which exception you want to ignore (e.g. `IndexError`). It's very bad practice to swallow *all* exceptions silently. – André Caron Feb 11 '12 at 20:25
  • 11
    Is the `a ? b : c` construct valid Python now?! I must have missed that... – Mark Byers Feb 11 '12 at 20:26
  • @ThiefMaster: How to specify an exception type? – hrishikeshp19 Feb 11 '12 at 20:29
  • To specify an exception type just subclass the `Exception` superclass and make sure you have a useful `__str__` method – snim2 Feb 11 '12 at 20:38
  • @hrishikeshp19 OK, I've left you a simple example to try out here: https://gist.github.com/1804191 – snim2 Feb 11 '12 at 21:02
  • @MarkByers : You are right. a ? b : c was not working...I changed that to if..else – hrishikeshp19 Feb 11 '12 at 21:32
  • Two questions in one? - Your question in the title, "Ignore exception in Python" has nothing to do with how to write a ternary in Python, right? Probably better if you separate them into two questions. You would then find that **both** questions have already been asked. For an answer to the ternary question, see [https://stackoverflow.com/questions/394809/does-python-have-a-ternary-conditional-operator#394814](https://stackoverflow.com/questions/394809#394814). – Henke Oct 15 '20 at 08:08
  • Another option is `with contextlib.suppress(MyException): ...` which saves one or two lines(though not performance) and reads a little nicer IMO. – Jesse Apr 20 '22 at 12:43

5 Answers5

27

pass is the keyword you are looking for.

David Heffernan
  • 601,492
  • 42
  • 1,072
  • 1,490
snim2
  • 4,004
  • 27
  • 44
  • theoratically you could add any expression *(e.g. `0`)* there, but `pass` is just more pythonic. – Niklas R Feb 11 '12 at 23:27
  • @NiklasR I'm not so sure. `0` is an expression and evaluates to `0`, `pass` is a statement. So, not exactly equivalent. – snim2 Feb 12 '12 at 00:18
  • But the interpreter wouldn't complain. `""` was possible, too, etc. – Niklas R Feb 12 '12 at 11:22
  • Again, `""` is an expression. The interpreter may not "complain" as such, but if you aren't going to do anything with the resultant value I would suggest it's bad practice to evaluate it unnecessarily, if for no other reason that it's confusing for anyone reading you code. – snim2 Feb 12 '12 at 12:02
10

Let us write the code properly.

  • We want to iterate over each cell of the grid. So do that. Don't create lists of numbers (range) that you iterate over and then use to index back in. Python's for-loops work directly with the container. It is convenient and easy to understand and good. Don't fight that.

  • There is no ?: construct in Python. There is a x if y else z construct, but that is not appropriate here. You are clearly trying to set count to the maximum of its current value and the cell value. There is a built-in function for that.

  • You really want the maximum of all of those cells. So ask for that directly; don't assume that you have to implement the high-water-mark algorithm yourself. You don't. (This also protects you from having to pick an initial value for count, which might be wrong.) We don't need to iterate with an explicit loop for this. We can specify the list of values to pass to max with a generator expression.

  • You want to "ignore" values that can't be converted to integers. Notwithstanding that there probably is something wrong with your other code if the existence of such values could possibly occur in the first place: we can simply make a test, and filter out the values that fail the test.

Thus:

def is_integral(value):
    try:
        int(value)
        return True
    except:
        return False


# Now, get the maximum of all the integral values:
count = max(
    int(cell) for row in grid for cell in row
    if is_integral(cell)
)
Karl Knechtel
  • 62,466
  • 11
  • 102
  • 153
  • Thats too high level for me right now. This is my first day. Thanks for suggestion though. – hrishikeshp19 Feb 11 '12 at 20:54
  • 3
    There is nothing conceptually difficult about this (btw, "high level" in programming generally means about the opposite of what you seem to think it means, although that's quite understandable). Writing the code this way is simpler than the way you're being shown how to write it. It requires **less** abstraction, because you aren't doing things like trying to figure out what this `range` object has to do with your original list. People who try to teach programming often have some very strange ideas of what's easy and what's hard. They teach things all out of order. :( – Karl Knechtel Feb 11 '12 at 21:19
  • +1 for addressing the real issues. – bgporter Feb 11 '12 at 21:50
  • +1 this makes a number of good points. – Gareth Latty Feb 11 '12 at 22:41
  • +1 the nicest and imho the most useful answer for the OP. – Niklas R Feb 11 '12 at 23:30
  • 2
    @KarlKnechtel: I'd put `return True` inside the `else` clause of the try..except statement. While it doesn't matter in that case, it'd teach a beginner the proper way (put only the code that might throw the exception into `try`, the exception-handling into `except`, the if-everything-went-alright into `else`) – ThiefMaster Feb 12 '12 at 00:20
  • 2
    @KarlKnechtel: I know what high level in context of programming languages means. In previous comment, by high level I was referring to complexity of "x for i in a for j in b" for a beginner. Your answer is great. Now, after using for loop several times, your approach seems a lot cleaner, safer, convenient option. Thanks. :) – hrishikeshp19 Feb 12 '12 at 08:57
5

You can use pass, but also ... is synonymous in Python 3.x, which can be nice for writing psuedocode.

I see a lot of people use pass where they truly need to do nothing, while using ... where they are using it as a placeholder.

class SomeInterface:
    def do_something(self):
        pass

class SomeImplementation(SomeInterface):
    def do_something(self)
        ...

This makes it easy to search for ... and find areas where you have unimplemented code, without the false positives from pass.

Note that passing on an exception is generally a bad practice, as you will virtually always want to act on exceptions. You should definitely, at the very least, specify the exact exception(s) you want to catch, as otherwise you will catch all exceptions, potentially causing bugs you can't detect if a different exception rears it's head.

Gareth Latty
  • 86,389
  • 17
  • 178
  • 183
  • 5
    `...` is not strictly synonymous, although it will have no effect. It's a naked expression, like putting `None` or `0` or `"foo"` there. `...` evaluates to the `Ellipsis` singleton. – Thomas K Feb 11 '12 at 21:35
  • @ThomasK True, synonymous was a poor choice or words on my part. It will work as pass does in this case. – Gareth Latty Feb 11 '12 at 22:39
4
for i in range(len(grid)):
    for j in range(len(grid[i])):
        try:
            count = count > int(grid[i][j]) ? count : int(grid[i][j])
        except:
            pass
yasar
  • 13,158
  • 28
  • 95
  • 160
  • 2
    That's always going to do nothing because there's a `SyntaxError` in the statement, and you're catching all exceptions. – kindall Feb 11 '12 at 20:35
  • 3
    @kindall: I don't think you can catch a SyntaxError that way; it should be raised at declaration, not during execution. – DSM Feb 11 '12 at 20:39
0
result = x if a > b else y

Is the ternary operator

The do nothing statement is

pass
maazza
  • 7,016
  • 15
  • 63
  • 96
Nickle
  • 367
  • 3
  • 5