An IOException is thrown and, for some reason, it's impossible to catch. Have a look at the code below. The stack trace says an IOException is thrown when calling the "apply"-method. The exception doesn't, however, get caught by the catch clause. When I try to catch an IOException instead, Eclipse complains saying: "Unreachable catch block for IOException. This exception is never thrown from the try statement body"
Why is this happening?
Code:
try {
action.apply();
}
catch (Exception e) {
System.out.println("Fail");
}
Here's the stacktrace:
java.io.IOException: Unable to download JavaScript from 'somesite' (status 404).
at com.gargoylesoftware.htmlunit.html.HtmlPage.loadJavaScriptFromUrl(HtmlPage.java:1023)
at com.gargoylesoftware.htmlunit.html.HtmlPage.loadExternalJavaScriptFile(HtmlPage.java:967)
at com.gargoylesoftware.htmlunit.html.HtmlScript.executeScriptIfNeeded(HtmlScript.java:353)
at com.gargoylesoftware.htmlunit.html.HtmlScript$1.execute(HtmlScript.java:225)
at com.gargoylesoftware.htmlunit.html.HtmlScript.onAllChildrenAddedToPage(HtmlScript.java:235)
at com.gargoylesoftware.htmlunit.html.HTMLParser$HtmlUnitDOMBuilder.endElement(HTMLParser.java:718)
at org.apache.xerces.parsers.AbstractSAXParser.endElement(Unknown Source)
at com.gargoylesoftware.htmlunit.html.HTMLParser$HtmlUnitDOMBuilder.endElement(HTMLParser.java:676)
at org.cyberneko.html.HTMLTagBalancer.callEndElement(HTMLTagBalancer.java:1136)
at org.cyberneko.html.HTMLTagBalancer.endElement(HTMLTagBalancer.java:1038)
at org.cyberneko.html.filters.DefaultFilter.endElement(DefaultFilter.java:206)
at org.cyberneko.html.filters.NamespaceBinder.endElement(NamespaceBinder.java:329)
at org.cyberneko.html.HTMLScanner$ContentScanner.scanEndElement(HTMLScanner.java:2999)
at org.cyberneko.html.HTMLScanner$ContentScanner.scan(HTMLScanner.java:1991)
at org.cyberneko.html.HTMLScanner.scanDocument(HTMLScanner.java:895)
at org.cyberneko.html.HTMLConfiguration.parse(HTMLConfiguration.java:499)
at org.cyberneko.html.HTMLConfiguration.parse(HTMLConfiguration.java:452)
at org.apache.xerces.parsers.XMLParser.parse(Unknown Source)
at com.gargoylesoftware.htmlunit.html.HTMLParser$HtmlUnitDOMBuilder.parse(HTMLParser.java:896)
at com.gargoylesoftware.htmlunit.html.HTMLParser.parse(HTMLParser.java:350)
at com.gargoylesoftware.htmlunit.html.HTMLParser.parseHtml(HTMLParser.java:304)
at com.gargoylesoftware.htmlunit.DefaultPageCreator.createHtmlPage(DefaultPageCreator.java:134)
at com.gargoylesoftware.htmlunit.DefaultPageCreator.createPage(DefaultPageCreator.java:101)
at com.gargoylesoftware.htmlunit.WebClient.loadWebResponseInto(WebClient.java:420)
at com.gargoylesoftware.htmlunit.WebClient.getPage(WebClient.java:303)
at com.gargoylesoftware.htmlunit.WebClient.getPage(WebClient.java:360)
at org.openqa.selenium.htmlunit.HtmlUnitDriver.get(HtmlUnitDriver.java:228)
at org.openqa.selenium.htmlunit.HtmlUnitDriver.get(HtmlUnitDriver.java:216)
at org.openqa.selenium.internal.seleniumemulation.Open.handleSeleneseCommand(Open.java:36)
at org.openqa.selenium.internal.seleniumemulation.Open.handleSeleneseCommand(Open.java:22)
at org.openqa.selenium.internal.seleniumemulation.SeleneseCommand.apply(SeleneseCommand.java:33)
at Action.runSeleniumAction(Action.java:235)
at SessionDriver.runSession(SessionDriver.java:192)
at SessionDriver.run(SessionDriver.java:123)
the apply() method fully handles the exception and does not rethrow it. If it did it would be marked as "public void apply() throws IOException".
The compiler warns you about this, since it would result in inaccurate error handling if it didn't.
Right, the apply() method itself isn't throwing that exception. Something else inside that apply method() is, and that something prints the complete stack trace instead of the "fail" message that you've decided is somehow better.
As you can see in the stacktrace, your code is missing, therefore you can't catch the exception. My guess is that SessionDriver.run() is called from a different thread.
Have you tried Selenium-RC? It should be able to catch these errors and pass them on to the test case.
You're using eclipse - so easiest way to get to the source of the exception is to run your application in debug mode and set a breakpoint on java.io.IOException. So whenever this exception is thrown somewhere in the running VM, eclipse will stop the application and show you thread, class and line of code (if available).
Related
What are IO Exceptions (java.io.IOException) and what causes them?
What methods/tools can be used to determine the cause so that you stop the exception from causing premature termination? What does this mean, and what can I do to fix this exception?
Java IOExceptions are Input/Output exceptions (I/O), and they occur whenever an input or output operation is failed or interpreted. For example, if you are trying to read in a file that does not exist, Java would throw an I/O exception.
When writing code that might throw an I/O exception, try writing the code in a try-catch block. You can read more about them here: https://docs.oracle.com/javase/tutorial/essential/exceptions/catch.html
Your catch block should look something like this:
try {
//do something
}catch(FileNotFoundException ex){
System.err.print("ERROR: File containing _______ information not found:\n");
ex.printStackTrace();
System.exit(1);
}
Here you go https://docs.oracle.com/javase/7/docs/api/java/io/IOException.html
IOException is thrown when an error occurred during an input-output operation. That can be reading/writing to a file, a stream (of any type), a network connection, connection with a queue, a database etc, pretty much anything that has to do with data transfer from your software to an external medium.
In order to fix it, you would want to see the stack trace of your exception or at least the message, to see exactly where the exception is thrown and why.
try {
methodThrowingIOException();
} catch (IOException e) {
System.out.println(e.getMessage()); //if you're using a logger, you can use that instead to print.
//e.printStackTrace(); //or print the full stack.
}
The error message that will be printed will likely show you what the issue is. If you add the error message here, I'll be able to give you more info on how to fix that specific IOException. Without that, no one can really give you a complete answer.
It is a very generic exception that a lot IO operation can cause. A best way is to read the Stack Trace. To continue the execution you can use the try-catch block to bypass the exception, but as you mention you should investigate into the cause.
To print the stack trace:
try {
// IO operation that could cause an exception
} catch (Exception ex) {
ex.printStackTrace();
}
IOException is usually a case in which the user inputs improper data into the program. This could be data types that the program can't handle or the name of a file that doesn't exist. When this happens, an exception (IOException) occurs telling the compiler that invalid input or invalid output has occurred.
Like others have said, you can use a try-catch statement to stop a premature termination.
try {
// Body of code
} catch (IOException e) {
e.printStackTrace();
}
After serving a few requests my eclipse has started breaking on processWorkerExit() method.
As per this link I know how to suppress the breaking of eclipse but is there any reason why the code is breaking on this line. Can there be a memory leak in such a case?
Tomcat 7.0.27
Eclipse 3.7.2
JDK 7.0.02
Answer is here: OpenJDK breaks on processWorkerExit with no breakpoint
In debug mode in eclipse by default, break on uncaught exceptions is
checked. Since you don't have a catch method here, it's likely that an
uncaught exception is being thrown and the debugger is breaking for
you immediately before the exception is thrown. You can turn it off in
preferences under Java->Debug.
The reason the debugger is stopping on that line is because there is an exception being thrown by the code within the try{} block, and that particular line of code is the next executable line of code after the exception is thrown. You can almost certainly see the stack trace of that exception in the console window, because by default an uncaught exception that bubbles up to Thread.run() will be sent to stderr.
As for your question about whether there can be a memory leak (or more likely, this being Java, a resource leak): the answer is yes, there could be. But there is nothing in that code to indicate that there is. If there were such a leak, it would almost certainly be because there is incorrect exception handling inside the task implementation.
I had this same problem. It breaks in your try/catch clause if you have one if you don't log the exception. Try inserting a breakpoint or output to LogCat like this :
try
{
//HERE I'VE PUT ALL THE FUNCTIONS THAT WORK FOR ME
Log.e("tag", "Sth passed!");
}
catch (Exception e)
{
//The task failed
Log.e("tag", e.getMessage());
}
If you don't have try/catch block put it like in above code. In LogCat you can see the last line of code that was run before exception it will help you to locate the error in your code just like this :
08-28 05:49:52.321: E/SQLiteDatabase(834): at java.lang.Thread.run(Thread.java:841)
My application has a delete user option. Now in order to check concurrency condition I tried the following use case
opened application in chrome and firefox browser.
deleted user in firefox
now trying to delete the same user in chrome browser I get exception org.hibernate.StaleObjectStateException .. which is right .. since I am trying to delete an object which doesn't exists. But I am not able to catch this exception
try{
getHibernateTemplate().delete(userObj);
} catch (StaleObjectStateException e) {
e.printStackTrace();
}
How do i catch this exception ??
You won't be able to catch it there, because it's not the delete call that throws the exception, but the flush of the session, which happens later (before the execution of a query, or before the transaction commit).
You should not catch this exception anyway, because when Hibernate throws an exception, you can't continue using the session anymore: it's in an unstable state. The only part of the application where such an exception can be caught is outside of the transaction, in order to display an error message to the user (or retry, but this won't be possible in this particular case).
You are catching StaleObjectStateException instead of StaleStateException :-)
UPDATE:
have a look at the stacktrace; assuming you're working in a transaction the exception might only be thrown when the transaction is committed.
The code in your question looks right on the face of it.
If that delete call actually throws that exception when executed, then your code will catch it. If it doesn't then the exception is actually being thrown in a different place ... or the exception that is being thrown is a different one.
I'd temporarily replace the catch with a catch of java.lang.Throwable to see if some other exception is propagating at that point. And add a trace print to see if the code is executing at all.
If you already have a stack trace, that will tell you where the exception is being thrown unless something really tricky is going on. You just need to catch it further up the stack.
writing a system in netbeans rcp - not sure if this matters, i just don't trust the rcp
We're approaching crunch time on our system and the following error keeps happening (sometimes it happens after 10 minutes, sometimes it runs for 2 days and then happens which is leading me to believe it could be a threading error)
we have a socket reader class which implements runnable - here is a sample of the code
#Override
public void run() {
while (!Thread.interrupted()) {
try {
/*
* can't display actual code
* reads data through socket and passes stream to a new handler class
* which uses reflection to create new object based off socket stream
* (none of this happens in a separate thread)
* (we're not holding a reference to the handler class - a new one is
* -created every iteration)
*
* at some point during the creation of this object, we get a socket
* closed exception happening at SocketInputStream.socketRead()
*/
} catch (Exception ex) {
cleanup();
}
}
}
what i expect to happen is that the socket exception should just be caught by the catch block and the cleanup executed
what ends up happening instead is i get a visible stack trace (pops up in the netbeans uncaught exception window and displays in the console) for java.net.SocketException socket closed - i cannot post the stack trace due to customer requirements
what else is strange is that in the actual socket input handler class we have the following method (this is the method that the exception is actually being thrown from)
public Abstract________ new________(Class<? extends Abstract________> clazz,
DataInput input) {
...
try {
// reflection code here
} catch (Exception ex) {
LOG.error("...");
throw new RuntimeException(ex);
}
...
}
if i try manually throwing the java.net.SocketException after the catch block the exception reads java.lang.RuntimeException: java.net.SocketException exception: socket closed
yet the stack trace that we receive randomly simply says java.net.SocketException: socket closed
this is leading me to believe that in our socket stream handling class it's not even catching the exception to begin with.
Does anybody have any input as to why this may be happening???
also - i am very sorry that i can't post the actual code, i'm not trying to be cryptic
so far the one thing i'm wondering about - i am somewhat familiar with reflection but not to a great extent - when i manually throw an exception it always gets caught by the try catch block - if an exception is thrown from something in reflection is there any way it could break the try catch contract - i don't see why it would but i mean, i'm honestly not sure and grasping for straws at this point
i have received permission to post an edited stack trace
in the MessageReader class there is no separate thread - the newMessage method is where the exception is being caught, wrapped into a RuntimeException and thrown up - the ____Reader is the socket reader with the while loop
both methods do show up in the stack trace
not sure if this will help
A thrown Error (java.lang.Error) may be bypassing your catch block (which is only catching Exceptions). Try catching Error and print out whatever debug statements you need. Don't forget to rethrow the error from the catch block.
It could also be that an Exception is being thrown in the catch block.
Two possibilities come to mind:
The exception is being caught higher up in the stack trace
or, the stack trace doesn't actually contain either of the methods you've pasted
I'm working on a project where an android application is communicating with a PHP server (WAMP) where some methods are implemented. We're using XMLRPC to handle client calls to server's methods. Anyway, even though everything happens fine, an exception is thrown when java tries to read the answer. So I would like to know if there is any way to read or save the server's response before java throws the exception (which is not really relevant) ?
Thanks in advance for your help !
The usual approach is to catch and handle this unchecked exception in your code. If you don't catch it, it will cause the application to stop.
Wrap the piece of code that causes the exception into a try/catch statement. This should allow you application to continue and you should be able to keep and process the response.
I do already set up a try/catch statement as you can see :
Integer result2 = null;
try {
Object[] dataParams = new Object[]{bytes, date, login};
result2 = ((Integer) client.execute("storeData", dataParams)).intValue();
System.out.println(result2.toString());
} catch (Exception ex)
{
ex.printStackTrace();
}
The storeData method is supposed to return an int. But as I get an exception, I can't see that response.
This is the error I get : [Fatal Error] :1:1: Content is not allowed in prolog.
I assume it's due to some bad characters in the xml response so that's why I'd like to get this response !