5

I'm a Java developer who's new to Python and I'm rewriting a Java class as a Python class. I'm trying to mimic the flow of the original class in my Python class as much as possible. The Java class has a few lines with,

    if(condition)
       throw new Exception("text here")

I've been looking over the Python documentation for exceptions and have not been able to find a Python equivalent to the Java syntax.

I've tried something (I think is close) with raise Exception("text here") by reading this StackOverflow post but it seems as if this is for use inside a try except block and will cause a jump from the try block to the except block; And I'm trying to avoid the try except blocks and just throw an exception.

A solution I think could work is this,

    try:
        if(condition):
           raise Exception("text here")
    except:
        ...

But I would like to know if there is an approach more closely related to the Java approach so that I can maintain as much of the flow as possible (have them look similar).

Community
  • 1
  • 1
Kyle Bridenstine
  • 6,055
  • 11
  • 62
  • 100

5 Answers5

5

Exception handling is perhaps the one non-trivial aspect aspect of Python that differs the least from Java, both in syntax and semantics. It's really just raise Exception("text here"). No, it doesn't have to be lexically within a try block. As in Java, it propagates up the call stack until it finally encounters a try block (with a matching except clause), or if there is no such block, it terminates the program and prints an error message.

2

Forget the try, your code would be exactly the equivalent without it

As others pointed it out: this throws (and doesn't catch or handle the exception):

condition = "Foo"
if(condition is "Foo"):
      raise Exception("FooException")

However if you want to handle it as you would if you had thrown in the java method then:

As explained in this documentation you will be throwing them by a method and then all you'll have to do is try the method and not every single condition in the method.

#!/usr/local/bin/python2.7

def foo(num):
    if (num == 2):
       raise Exception("2Exception")
    if (num == 3):
       raise Exception("Numception")

def handleError(e):
    print(e)

def main():
  try:
    foo(3)
    print("no errors")
  except Exception, e:
    handleError(e)


if __name__ == "__main__":
    main()
Kyle Bridenstine
  • 6,055
  • 11
  • 62
  • 100
Mansueli
  • 6,223
  • 8
  • 33
  • 57
  • This is very clear and concise which is why I accepted it as the answer. One quick question that's not a big deal, when I use your code my print out has a strange comma after the text Exception('Something Happened',) Do you know why? (Again, this answer was exactly what I needed!) – Kyle Bridenstine Jul 14 '14 at 20:52
  • 1
    @2g7hgfdr8324, it must be something in your environment if you test it [here](http://www.compileonline.com/execute_python_online.php) you won't see the comma that you are seeing for some reason in your machine. – Mansueli Jul 14 '14 at 21:32
1
if (condition):    
    raise Exception("test")

will accomplish what you want. Give it a try.

Paul Becotte
  • 9,767
  • 3
  • 34
  • 42
1

If you don't want to catch the exception, then this is probably what you want:

if condition:
    raise Exception("something bad happened!")

If you DO want to catch the exception, then using Python's try/except is the way to go.

Mike Driscoll
  • 32,629
  • 8
  • 45
  • 88
1
raise StandardError("message")

is perfectly valid code anywhere. In fact, raising an exception within a try/except block is usually only done to show case error handling. It doesn't actually make sense to raise and handle an exception within the same function.

Midnighter
  • 3,771
  • 2
  • 29
  • 43
  • 3
    `StandardError` doesn't exist in Python 3, is pretty obscure in Python 2, and is intended as superclass for most exceptions (to allow catching "errors" without catching "control flow exceptions") rather than being instantiated. `Exception` is a closer equivalent to Java. –  Jul 14 '14 at 20:01