Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java - How to do Python's Try Except 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.

like image 561
Greg Avatar asked Aug 13 '10 15:08

Greg


People also ask

How do you use except and try in Python?

The try block lets you test a block of code for errors. The except block lets you handle the error. The else block lets you execute code when there is no error. The finally block lets you execute code, regardless of the result of the try- and except blocks.

Can else be used with except in Python?

Use the Python try... except...else statement provides you with a way to control the flow of the program in case of exceptions. The else clause executes if no exception occurs in the try clause. If so, the else clause executes after the try clause and before the finally clause.

How do you create an exception in Python?

In Python, exceptions can be handled using a try statement. The critical operation which can raise an exception is placed inside the try clause. The code that handles the exceptions is written in the except clause. We can thus choose what operations to perform once we have caught the exception.

How do you handle multiple try except in Python?

Python Multiple Exception in one Except You can also have one except block handle multiple exceptions. To do this, use parentheses. Without that, the interpreter will return a syntax error.


1 Answers

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 } if (success) {     // equivalent of Python else goes here } 
like image 88
Ryan Ische Avatar answered Sep 19 '22 15:09

Ryan Ische