1

Is there a way to shorten the following scenario so i don't have to use an ugly nested try except statement?

class Error(Exception):
    def __init__(self):
        print("That did not work")
try:
    try:
        gblgbl
    except:
        raise Error
except Error:
    pass

What i want can be described as following pseudo code:

Try something:
    something
if something went wrong:
    raise Error
catch Error:
    what to do if error occours

I don't want to raise the error if the try statement succeeds, however if i raise an exception in the exception statement like this:

try:
    gblgbl
except:
    raise Error
except Error:
    pass

it can't be caught with an other except, since there is already an except that caught the python exception and the interpreter throws a SyntaxError.

Am i missing something obvious?

I'm aware that you probably would never use this in an actual program, but i'm curious about the theory.

martineau
  • 119,623
  • 25
  • 170
  • 301
L.S.
  • 476
  • 4
  • 10
  • I think this already have an answer through http://stackoverflow.com/questions/1319615/proper-way-to-declare-custom-exceptions-in-modern-python – jefcabatingan Feb 09 '16 at 15:36
  • In addition to the question mentioned by @jefcabatingan [this blog post](https://www.codementor.io/python/tutorial/how-to-write-python-custom-exceptions) might be interesting, too. – albert Feb 09 '16 at 15:39
  • All you're accomplishing is translating _any_ except when `gblgbl` executes into an `Error` exception and then immediately handling it. You don't really need the inner exception clause to do that. – martineau Feb 09 '16 at 15:56

2 Answers2

1

There is no reason to use an exception here. The following (pseudo-)code achieves the same thing.

try:
    gblgbl
except:
    pass

Note however that it generally is a bad idea to catch all exceptions, since for instance the KeyboardInterrupt Exception will also be caught and the program can thus not be interrupted using Ctrl-c

David Zwicker
  • 23,581
  • 6
  • 62
  • 77
  • 1
    Sure, but i could do things like count the times this exception occurred in a class variable of the Error class. – L.S. Feb 09 '16 at 15:39
  • But this still misses the point of an exception, which is to signal an error to the caller. Your example could also be achieved with any other counter and does not require a separate `try`-`except`. – David Zwicker Feb 09 '16 at 15:41
-1

Create custom exceptions?

The Python Tutorial has a section on User-defined Exceptions

dsh
  • 12,037
  • 3
  • 33
  • 51