Imageiio can't create imageinput stream - java

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.

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

How to fix unreported IO Exception. Trying to read a specific line from a .txt file [duplicate]

This question already has an answer here:
What does "error: unreported exception <XXX>; must be caught or declared to be thrown" mean and how do I fix it?
(1 answer)
Closed 8 months ago.
While learning Java I stumble upon this error quite often. It goes like this:
Unreported exception java.io.FileNotFound exception; must be caught or declared to be thrown.
java.io.FileNotFound is just an example, I've seen many different ones. In this particular case, code causing the error is:
OutputStream out = new BufferedOutputStream(new FileOutputStream(new File("myfile.pdf")));
Error always disappears and code compiles & runs successfully once I put the statement inside try/catch block. Sometimes it's good enough for me, but sometimes not.
First, examples I'm learning from do not always use try/catch and should work nevertheless, apparently.
Whats more important, sometimes when I put whole code inside try/catch it cannot work at all. E.g. in this particular case I need to out.close(); in finally{ } block; but if the statement above itself is inside the try{ }, finally{} doesnt "see" out and thus cannot close it.
My first idea was to import java.io.FileNotFound; or another relevant exception, but it didnt help.
What you're referring to are checked exceptions, meaning they must be declared or handled. The standard construct for dealing with files in Java looks something like this:
InputStream in = null;
try {
in = new InputStream(...);
// do stuff
} catch (IOException e) {
// do whatever
} finally {
if (in != null) {
try {
in.close();
} catch (Exception e) {
}
}
}
Is it ugly? Sure. Is it verbose? Sure. Java 7 will make it a little better with ARM blocks but until then you're stuck with the above.
You can also let the caller handle exceptions:
public void doStuff() throws IOException {
InputStream in = new InputStream(...);
// do stuff
in.close();
}
although even then the close() should probably be wrapped in a finally block.
But the above function declaration says that this method can throw an IOException. Since that's a checked exception the caller of this function will need to catch it (or declare it so its caller can deal with it and so on).
Java's checked exceptions make programmers address issues like this. (That's a good thing in my opinion, even if sweeping bugs under the carpet is easier.)
You should take some appropriate action if a failure occurs. Typically the handling should be at a different layer from where the exception was thrown.
Resource should be handled correctly, which takes the form:
acquire();
try {
use();
} finally {
release();
}
Never put the acquire() within the try block. Never put anything between the acquire() and try (other than a simple assign). Do not attempt to release multiple resources in a single finally block.
So, we have two different issues. Unfortunately the Java syntax mixes up the two. The correct way to write such code is:
try {
final FileOutputStream rawOut = new FileOutputStream(file);
try {
OutputStream out = new BufferedOutputStream(rawOut);
...
out.flush();
} finally {
rawOut.close();
}
} catch (FileNotFoundException exc) {
...do something not being able to create file...
} catch (IOException exc) {
...handle create file but borked - oops...
}

Java know in finally that exception thrown without any variable [duplicate]

In Java, is there an elegant way to detect if an exception occurred prior to running the finally block? When dealing with "close()" statements, it's common to need exception handling within the finally block. Ideally, we'd want to maintain both exceptions and propagate them up (as both of them may contain useful information). The only way I can think of to do this is to have a variable outside the try-catch-finally scope to save a reference to a thrown exception. Then propagate the "saved" exception up with any that occur in the finally block.
Is there a more elegant way of doing this? Perhaps an API call that will reveal this?
Here's some rough code of what I'm talking about:
Throwable t = null;
try {
stream.write(buffer);
} catch(IOException e) {
t = e; //Need to save this exception for finally
throw e;
} finally {
try {
stream.close(); //may throw exception
} catch(IOException e) {
//Is there something better than saving the exception from the exception block?
if(t!=null) {
//propagate the read exception as the "cause"--not great, but you see what I mean.
throw new IOException("Could not close in finally block: " + e.getMessage(),t);
} else {
throw e; //just pass it up
}
}//end close
}
Obviously, there are a number of other similar kludges that might involve saving the exception as an member variable, returning it from a method, etc... but I'm looking for something a bit more elegant.
Maybe something like Thread.getPendingException() or something similar? For that matter, is there an elegant solution in other languages?
This question actually spawned from comments in another question that raised an interesting question.
Your idea about setting a variable outside the scope of the try/catch/finally is correct.
There cannot be more than one exception propagating at once.
Instead of using a Boolean flag, I would store a reference to the Exception object.
That way, you not only have a way to check whether an exception occurred (the object will be null if no exception occurred), but you'll also have access to the exception object itself in your finally block if an exception did occur. You just have to remember to set the error object in all your catch blocks (iff rethrowing the error).
I think this is a missing C# language feature that should be added. The finally block should support a reference to the base Exception class similar to how the catch block supports it, so that a reference to the propagating exception is available to the finally block. This would be an easy task for the compiler, saving us the work of manually creating a local Exception variable and remembering to manually set its value before re-throwing an error, as well as preventing us from making the mistake of setting the Exception variable when not re-throwing an error (remember, it's only the uncaught exceptions we want to make visible to the finally block).
finally (Exception main_exception)
{
try
{
//cleanup that may throw an error (absolutely unpredictably)
}
catch (Exception err)
{
//Instead of throwing another error,
//just add data to main exception mentioning that an error occurred in the finally block!
main_exception.Data.Add( "finally_error", err );
//main exception propagates from finally block normally, with additional data
}
}
As demonstrated above... the reason that I'd like the exception available in the finally block, is that if my finally block did catch an exception of its own, then instead of overwriting the main exception by throwing a new error (bad) or just ignoring the error (also bad), it could add the error as additional data to the original error.
You could always set a boolean flag in your catch(es). I don't know of any "slick" way to do it, but then I'm more of a .Net guy.
Use logging...
try {
stream.write(buffer);
} catch(IOException ex) {
if (LOG.isErrorEnabled()) { // You can use log level whatever you want
LOG.error("Something wrong: " + ex.getMessage(), ex);
}
throw ex;
} finally {
if (stream != null) {
try {
stream.close();
} catch (IOException ex) {
if (LOG.isWarnEnabled()) {
LOG.warn("Could not close in finally block", ex);
}
}
}
}
In vb.net, it's possible to use a "Catch...When" statement to grab an exception to a local variable without having to actually catch it. This has a number of advantages. Among them:
If nothing is going to 'ultimately' catch the exception, an unhandled exception trap will be fired from the spot of the original exception. Much nicer than having the debugger trap at the last rethrow, especially since information that might be needed for debugging won't yet have gone out of scope or been swept up by 'finally' statements.
Although a rethrow won't clear the stack trace the way "Throw Ex" would, it will still often jinx the stack trace. If the exception isn't caught, the stack trace will be clean.
Because this feature is unsupported in vb, it may be helpful to write a vb wrapper to implement the code in C (e.g. given a MethodInvoker and an Action(Of Exception), perform the MethodInvoker within a "Try" and the Action in a "Finally".
One interesting quirk: it's possible for the Catch-When to see an exception which will end up getting overwritten by a Finally-clause exception. In some cases, this may be a good thing; in other cases it may be confusing. In any event, it's something to be aware of.

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

Categories