Reputation: 6393
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).
Upvotes: 5
Views: 2671
Reputation: 6984
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()
Upvotes: 2
Reputation: 33091
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.
Upvotes: 1
Reputation: 3881
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.
Upvotes: 1
Reputation:
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.
Upvotes: 5
Reputation: 9997
if (condition):
raise Exception("test")
will accomplish what you want. Give it a try.
Upvotes: 1