How do I do a try except else in Java like I would in Python?
Example:
try:
something()
except SomethingException,err:
print 'error'
else:
print 'succeeded'
I see try and catch mentioned but nothing else.
How do I do a try except else in Java like I would in Python?
Example:
try:
something()
except SomethingException,err:
print 'error'
else:
print 'succeeded'
I see try and catch mentioned but nothing else.
While there is no built-in way to do that exact thing. You can do something similar to achieve similar results. The comments explain why this isn't the exact same thing.
If the execution of the somethingThatCouldError()
passes, YAY!!
will be printed. If there is an error, SAD
will be printed.
try {
somethingThatCouldError();
System.out.println("YAY!!");
// More general, code that needs to be executed in the case of success
} catch (Exception e) {
System.out.println("SAD");
// code for the failure case
}
This way is a little less explicit than Python. But it achieves the same effect.
Java doesn't have the equivalent of an "else" clause for Try/Catch. Simply put the content of your "else" clause at the end of your Try block. [Just like in @Justin 'jjnguy' Nelson's answer. :)]
I'm not entirely convinced that I like it, but this would be equivalent of Python's else. It eliminates the problem's identified with putting the success code at the end of the try block.
bool success = true;
try {
something();
} catch (Exception e) {
success = false;
// other exception handling
} finally {
if (success) {
// equivalent of Python else goes here
}
}
EDIT: I don't think the finally is really necessary, since the purpose of the finally block is to execute regardless of any exceptions being thrown in the try block. Since you only want the code to execute on success, you could just have the if statement occur after the try-catch block. Ultimately, it comes down to putting the right code in the try block.