Does Python have a Java equivalent of throw new Exception("text here")

exception, python

Solution

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()

Problem

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).

Original source

Related problems