Java - How to do Python's Try Except Else - java

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.

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
}

What about this?
try {
something();
} catch (Exception e) {
// exception handling
return;
}
// equivalent of Python else goes here
Sure, there are some cases where you want to put more code after the try/catch/else and this solution don't fit there, but it works if it's the only try/catch block in your method.

While Ryan's answer of tracking errors with boolean(s) is nice, I think using a "logic block" to "skip forward" is better in this case.
In Java, you are allowed to create arbitrary context blocks (scopes) using <optional-label-name followed by ':'>{...} and assign labels to them. You can than call break <labelname>;
Here is an example of what I mean that you can play with:
private static void trycatchelsetest(boolean err) {
myLogicBlock: {
try {
System.out.println("TRY");
{ //unlabeled block for demonstration
if(err)
throw new IOException("HELLO!");
}
} catch(IOException e) {
System.out.println("CATCH");
break myLogicBlock;
} finally {
System.out.println("FINALLY");
}
System.out.println("ELSE");
}
System.out.println("END");
}
The reason Try doesn't have an else is because it is meant to catch a specific error from a specific block of code, which is either handled (usually by setting a default or returning), or bubbled up (and finally is offered only to make sure resources aren't leaked because of the interrupt, even if you break out). In the break example above, we are handling the exception by skipping the block of code that is no longer relevant because of the error (skipping forward to the next logical step). The boolean example by Ryan handles it by noting the error happened, and letting latter parts of the code react to it happening after the fact.
I think the logic block is better than the boolean approach (as long as you have no complex logic based on what errors have been thrown) because it doesn't require the reader to know the entire function to understand what happens. They see break <labelname>; and know that the program will effectively skip forward to the end of that block. The boolean requires the programmer to track down everything that makes decisions on it.
Obviously, "Skip-forward" and Boolean tracking each have their own advantages, and will usually be more a style choice.

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.

Related

SonarQube rule "Methods returns should not be invariant" with catch block

I'm using latest SonarQube server 9.4 and it constantly reports "Refactor this method to not always return the same value." - java:S3516 in piece of code like this:
try
{
FileUtils.moveFile(dcomExportFile, destination);
}
catch(IOException e)
{
Logger.error(this, "Could not move file {} to {}, future job runs might fail as well",
dcomExportFile.getAbsolutePath(), destination.getAbsolutePath());
return false;
}
return true;
Which is very strange because method FileUtils.moveFile can throw IOException and in this case method returns false.
Any idea?
Thx!
I would move the return false statement to outside and after the catch (where return true is now). And move the return true to immediately follow the Fileutils call in the try block, like this:
try
{
FileUtils.moveFile(dcomExportFile, destination);
return true;
}
catch(IOException e)
{
Logger.error(this, "Could not move file {} to {}, future job runs might fail as well",
dcomExportFile.getAbsolutePath(), destination.getAbsolutePath());
}
return false;
It's confusing and arguably bad style to return from within a catch block anyway.
I'm not sure that in this case not letting the exception be thrown is a great idea because this seems like the sort of error I would want to bubble up, where having a return value lets it get lost too easily. Maybe it's not so bad if logging the error is the only thing the code does to handle this.
I think it may not be good idea to just catch & log exception & return false. You might need to throw exception back to caller of your method.
Good example which comes in my mind is list.add(..) where if operation is success it returns true but in case of any failure it throws exceptions to caller instead of returning false.
I found solution - scanning with correct sonar.java.libraries path resolves this issue.

Is there a point to handle exceptions in selenium besides for logging purposes?

I am finding it hard to understand the point of exception handling in selenium.
For example, if I try to click on an element, and the element could not be found then NoSuchElementException occurs.
I can catch the exception, throw new RunTimeException, or do nothing. The result will be the same ( the program will fail and stop ).
Why would I bother to handle such an exception?
Am I missing something here?
thanks
public void clickOnElement(MobileElement element, Integer waitInSeconds){
waitInSeconds = (waitInSeconds != null ? waitInSeconds : this.secondsToWait);
try {
waitFor(ExpectedConditions.elementToBeClickable(element),waitInSeconds);
element.click();
} catch (Exception e) {
System.out.println("Could not click on element");
e.printStackTrace();
}
}
Exception handling for Selenium is a great way to proof your tests against unexpected conditions. For example, you can try to find the element again if it is no longer attached to the page, for example after a javascript is executed that changes something in the element.
try{
driver.findElement(By.id("MyId")).click();
} catch (StaleElementReferenceException e){
driver.findElement(By.id("MyId")).click();
}
Or, for example, you can ignore if an element does not appear, for example, a GDPR overlay at the top of the page after logging in.
try {
wait.until(ExpectedConditions.presenceOfElementLocated(By.id("gdpr_overlay")));
} catch (TimeoutException ignored){
}
This will ignore the exception thrown by the wait if the overlay does not appear and continue to run your test.
Exceptions are very useful features, far more useful than just for logging, you should look it up.
You can do whatever you want in the catch block, you can try to click a different element if the first one failed, redirect to another page... The possibilities are endless really.
Advice: Avoid generic exceptions, you should catch specific exceptions and react accordingly, and in the last catch block you can do generic Exception e and throw an error.
Firstly ExceptionHandling is not a concept of Selenium but it is related to JAVA. Now coming to the usage of handling exceptions it has a lot of depth to the concept which you will understand while constructing frameworks but as of now it is important to understand by handling exceptions you can continue to execute your code without JVM terminating the rest when it comes across an exception.
try{
}
catch{
}
finally
{
}
Finally is also very helpful when you always want to execute a block of code irrespective of whether ur scenario is going to pass or fail for example like driver.close().
Hope that helped ... Happy coding :)

Putting try catch finally block inside another finally block

try {
} catch() {}
finally {
try {
} catch() { }
finally { }
}
Is it good to have the code like above?
Yes, you can do this.
Actually, you are even required to do it when dealing with streams you want to close properly:
InputStream in = /* ... */;
try {
} catch (...) {
} finally {
try {
in.close();
} catch (...) {
} finally {
}
}
I don't see any case in which this would be a bad practice
For readability you can factor out the nested try-catch in to a separate method, like:
try{
}catch(){}
finally{
cleanup();
}
And the second try-catch can be inside the cleanup method.
To support the above pattern in IO package, JAVA6 introduces a new class called Closeable that all streams implement, so that you can have a single cleanup method as follows:
public static boolean cleanup(Closeable stream)
{
try{
stream.close();
return true;
}catch(){
return false;
}
}
It is best to avoid it when you can, but sometimes it may be necessary. If you tell us more about why you think you need this, we may be able to give better answers :-)
One reason to think about may be to commit a transaction in the finally block, when the commit operation itself may throw an exception.
It is important to note that exceptions thrown inside a finally block may easily shadow exceptions thrown earlier, within the try block, unless handled properly. Thus such nested try/catch blocks are sometimes the way to go. However, as others have noted, to improve readability, it is advisable to extract the insides of the finally block into a separate method.
It's ugly, but there are cases where you can't avoid it, especially in resource clean up where you have dependent resources and the clean up of one resource can throw an exception.
A typical example is tidying up ResultSet, Statement and Connection objects in JDBC code. Closing the ResultSet can throw an exception, but we'd still like to continue and close the Statement and Connection
Looks ugly but sometimes it's the way to go. Depending on the code consider to extract a method with the second try-catch-finally block.

What is the gist of finally block in Java?

I think on the following examples; but could not figure out what the importance of the finally block is. Can you tell me the difference of the executions of these two code samples? Also a real life example can be helpful.
Sample 1:
try{
// some code 1
}catch(Exception ex){
// print exception
}finally{
// some code 2
}
Sample 2:
try{
// some code 1
}catch(Exception ex){
// print exception
}
// some code 2
There is a big difference in the two snippets you've presented, e.g. when the catch block itself throws an exception, the finally block would still be executed by its semantics.
That is the following snippet prints "Finally!", but not "What about me???":
try {
throw null; // throws NullPointerException!
} catch (Exception e) {
int oops = 1/0; // throws ArithmeticException!
} finally {
System.out.println("Finally!"); // still gets executed!
}
System.out.println("What about me???"); // doesn't get executed!
Generally speaking, the finally of a try block practically always gets executed. There's no such guarantee for any code following the try block.
But what if my catch block is just a simple print statement?
There's still no guarantee that it won't throw something. Something could still go wrong in e.g. the construction for the exception detailed message.
Even if you make a best effort guarantee that the catch code is "safe" and the code following the try statement will always be executed, the question then becomes "Why?". Why avoid finally but then try so hard to replicate its semantics?
finally semantics is guaranteed, requiring no burden of proof from either the writer or the reader of the code. Precisely because of this, it's idiomatic to use finally block to put mandatory "clean-up" code. Using finally guarantees correctness and enhance both writability and readability.
The finally block is executed even if e.g. an Error is thrown, which is not caught by the catch block in your example. So you can put cleanup code in the finally block, which should be run always, regardless of the outcome of the operations in the try and catch blocks.
Note that usually catch blocks catch more specific types of exceptions - often only checked exceptions -, so in most cases the difference between the two code examples above is very definite.
Update: you may say that your catch block can never throw an exception, so finally is not needed. However, note two things:
this is only the current state of the code, and it can change in the future - can you guarantee that the future programmer who adds some potentially exception-throwing code in the catch block, will remember to put the cleanup code after it into a finally block?
try-catch-finally is a programming idiom which makes it easier for people reading the code to understand what's going on. If you don't use the common idiom, you risk misunderstanding, thus bugs on the long term.
You use the finally block in order to cleanup and run any code that should run whether an exception was thrown (and caught) or not. This includes code that you have in the catch block.
it is helpful when we want to free up the resources we used in try block. So the only place to execute them without missing at any case is finally block. Since if exception is thrown, java does not execute code which immediate after that. it directly jump to the catch block.
Note that you can have even try-finally without a catch:
try{
// some code
}finally{
// cleanup code
}
An example therefore could be a method that wants to propagate exceptions to the caller, but still needs clean up code, like releasing a look.
In case where the statements in try block throw unchecked exceptions, finally block will get executed allowing programmer to take relevant actions.
In real life, the finally block is used to close opened resources even if an exception occurs.
For example, when you read (or write) a file, when you access to a database, etc.
public void readFile(String fileName) {
FileReader fr;
BufferedFileReader bfr;
try {
fr = new FileReader(fileName);
bfr = new BufferedFileReader(fr);
// ...
} catch (IOException ioe) {
// ...
} finally {
// TO ENSURE THAT THE READERS ARE CLOSED IN ALL CASES
if (bfr != null) {
try {
bfr.close();
} catch (IOException ignoredIOE) {}
}
if (fr != null) {
try {
fr.close();
} catch (IOException ignoredIOE) {}
}
}
}

Imageiio can't create imageinput stream

When using imageio.imageio.read iget a can't create ImageInputStream. I have a catch exception around it so the program survives but i was wondering if theres a way to put an if statement round it that checks to see if it falied and then attempt to read it again if it did.
basically asking if there is a test for exceptions?
try...catch is the test for exceptions. If you really want to treat your exception as a loop control mechanism, you can wrap it up something like this:
boolean success = false;
do {
try {
// do imageIO stuff
success = true; // this statement only reached if no exception
} catch (Exception e) {
System.err.println(e);
}
} while (!success);
As doublep hints, this is a pretty senseless implementation because it's unlikely for the problem to go away from one iteration of the loop to the next, so your program will probably just loop endlessly printing error messages.

Categories