Ok here is my code fragment:
try
{
res = gfSQL.doSQL("SELECT TIMESTAMP, MSGLEVEL, APPLICATION, STREAM, THREADID, " +
" THREADNAME, REQUESTID, MESSAGE, ID, PROCESSED" +
" FROM GFLOG where PROCESSED = 'N'" +
" ORDER BY TIMESTAMP, ID");
} catch ( SQLException e) {
e.printStackTrace();
System.exit(128);
}
if (! res.first()) { <<<---- FLAGGED STATEMENT
// no data to process
System.err.println("No data found to process\n");
return;
}
Now java is flagging the indicating statement (and just about everyone after it) with a 'Unhandled exception type SQLException). gfSQL.doSQL throws this exception and is defined with:
public ResultSet doSQL(String sqlCommand) throws SQLException
{
The funny thing is - if I repeat the 'catch' block like so:
try
{
res = gfSQL.doSQL("SELECT TIMESTAMP, MSGLEVEL, APPLICATION, STREAM, THREADID, " +
" THREADNAME, REQUESTID, MESSAGE, ID, PROCESSED" +
" FROM GFLOG where PROCESSED = 'N'" +
" ORDER BY TIMESTAMP, ID");
} catch ( SQLException e) {
e.printStackTrace();
System.exit(128);
} catch ( SQLException e) {
e.printStackTrace();
System.exit(128);
}
if (! res.first()) {
// no data to process
No 'unhandled' error is flagged. (however the duplicate catch phrase is flagged as an 'unreachable catch block - SQLException is already handled' of course.)
Any ideas why Java sees the catch in one instance but not the other? Or am I missing something?
Well, gfSQL.doSQL()can throw a SQLException, and you're catching it.
But res.first()can also throw a SQLException, and you're not catching it, since this instruction is out of the try block. That's why you get the compiler error.
res.first() should be in the try block as it can throw an exception:
try {
res = // ...
if(!res.first()) {
// ...
}
} catch ( SQLException e) {
// ...
}
Related
#Test
public void test() throws Exception {
driver.navigate().to(someurl);
Thread.sleep(2000);
try {
obj.assertPageTitle1("Title");
obj.clickButton();
obj.assertPageTitle2("Title");
obj.assertPageTitle3("TitleWithError");
} catch (Error e) {
System.out.println("Exception is - " + e);
}
}
Log: Exception is - java.lang.AssertionError
How can I add line number(where was error) in the message which show error in log?
The most recent called method is appeared in the stacktrace's first element.
Try
e.getStackTrace()[0].getLineNumber();
Small example:
try {
String s = null;
s.toLowerCase();
} catch (Exception e) {
System.out.println("Line number is: " + e.getStackTrace()[0].getLineNumber());
}
Note: You can always print stacktrace by using e.printStackTrace() to see the more verbose result.
I am connecting to a website using Jsoup. I have inserted a .timeout to check if the website times out.
Because I already handle IOException, my IDE is not allowing me to put another catch for SocketTimeOutException, which is fair, I guess.
Is there a way to tell from IOException what is the error?
I'd like to have specific debugging output for different errors, so that I can keep the code clean and efficient.
Here is my code (yes, some variables are missing, they are pretty simple though and not really necessary):
Document doc = null;
try
{
doc = Jsoup.connect(Url).proxy(proxy).userAgent(userAgent).timeout(10000).get();
}
catch (IOException e)
{
if (...)
{
if(specificThread.running == false) {
System.out.println("Thread got interrupted! Link visited -> "+ Url);
Thread.currentThread().interrupt();
}
try
{
System.out.println("Localhost detected! If this happens, you're stupid");
doc = Jsoup.connect(Url).userAgent(userAgent).get();
}
catch (IOException e1)
{
System.out.println("Couldn't connect to " + Url + " , localhost was detected.");
e1.printStackTrace();
System.exit(-1);
}
catch (java.lang.IllegalArgumentException error)
{
System.out.println("Malformed URL detected -> " + Url) ;
}
}
else
{
System.out.println("Couldn't connect to " + Url);
e.printStackTrace();
}
}
catch (java.lang.IllegalArgumentException error)
{
System.out.println("Malformed URL detected -> " + Url);
}
catch (java.net.SocketTimeoutException error) //IDE Is blocking this
{
//Handle error here
}
Is it possible to do this?
Put the catch for the SocketTimeoutException before the catch for the IOException.
Exception handling works by looking through a table until a matching exception type is found. As such, more specific exceptions have to come before more general exceptions, in order that they can be matched.
This is described in JLS Sec 14.21, "Unreachable Statements":
It is a compile-time error if a statement cannot be executed because it is unreachable.
...
A catch block C is reachable iff both of the following are true:
...
There is no earlier catch block A in the try statement such that the type of C's parameter is the same as or a subclass of the type of A's parameter.
So, you just need to make sure there is no earlier catch block catching a superclass parameter.
I have a method in a j2me project in which, after 2 days of normal working, it collapses. The error presented is the following:
Contacting website...
java.lang.OutOfMemoryError
(stack trace incomplete)
The said method is the one used to communicate with a website. It receives a string and a mode selector (i=1 or smth else) and procedes with the request. Here's the code:
void enviarPost(int i, String comando)throws IOException, IllegalStateException, IllegalArgumentException, ATCommandFailedException{
System.out.println("Contacting website...");
if(i == 1)
{
url = "http://websitedummy.com.pl/index.php?IMEI=" + imeiX + "&IP=" + ipX;
}
//53543D303B44723D4E616F
else
{
url2 = comando;
url = "http://websitedummy.com.pl/index.php?data={\"IMEI\":\""+imeiX+"\",\"TS\":\"20/04/13-08:31:44\",\"SER\":\""+url2+"\"}";
}
try {
Thread.sleep(1000);
connection = (HttpConnection) Connector.open(url);
Thread.sleep(500);
connection.setRequestMethod(HttpConnection.GET);
Thread.sleep(500);
connection.setRequestProperty("Content-Type", "text/plain");
Thread.sleep(500);
int con = 0;
try{
con = connection.getResponseCode();
} catch (Exception e4)
{
System.out.println(e4);
}
if (con == HttpConnection.HTTP_OK) {
System.out.println("Vamos");
inputstream_ = connection.openInputStream();
int ch;
while ((ch = inputstream_.read()) != -1 ) {
dataReceived.append((char) ch);
}
System.out.println("Atualizado.");
acabouatualizar=1;
inputstream_.close();
connection.close();
} else {
System.out.println("Error");
// Connection not ok
}
} catch (Exception e) {
System.out.println("EXCEÇÂO 1 - " + e);
} finally {
if (inputstream_ != null) {
try {
inputstream_.close();
} catch (Exception e1) {
System.out.println("EXCEÇÂO 2- " + e1);
}
}
if (connection == null) {
try {
System.out.println("Fechou conexao.");
connection.close();
} catch (Exception e2) {
System.out.println("EXCEÇÂO 3- " + e2);
}
}
}
}
To solve the issue i thought about clearing all the variables used in the connection. The problem is I kind of have to be almost sure what the issue is because the error will take 2 days to happen and this will cost me a great amount of time.
Any suggestions?
Thanks guys.
It's hard to say what cause the outOfMemoryError exception, but there are ways to work with it. The root cause of this problem can refer to this:
there isn't enough memory in the JVM;
native threads aren't enough, unable to create more threads;
You can use jconsole to debug with this problem, which is a tool to have a look at the memory, threads, classes usage in the JVM. Besides, the exception message can point out the root cause in some cases.
System.out.println("======================================");
System.out.println("List of Ships and their revenue");
System.out.println("======================================");
try
{
inputStream = new ObjectInputStream (new FileInputStream (fileName));
}
catch (Exception e)
{
System.out.println("Problem");
}
try
{
while (true)
{
Ship copyObject = (Ship)inputStream.readObject();
System.out.println(copyObject.getShipName() + " " + copyObject.getRevenue());// fix format later
}
}
catch (EOFException e)
{
}
catch (Exception e)
{
}
I want to retrieve data from a binary file, which I definitely know that I has data as a objects. But the result of the program is only the below:
=================================
List of Ships and their revenue
=================================
It probably means that there is something wrong with the try block. Note that this is just part of my program, which relates to the result I want to get. Ship is a superclass of the classes to which the object in the file belong. (update: I just print the exception, but no exception is thrown).
By the looks of it you are in an infinite loop which dies with an exception which results in no output. Try doing the following instead of the giant second try catch block.
while(true) {
try{
Ship copyObject = (Ship)inputStream.readObject();
System.out.println(copyObject.getShipName() + " " + copyObject.getRevenue());
}
catch(Exception ex) {
System.out.println("No more ships");
break;
}
}
I have the following java code:
if (ps.executeUpdate() != 1)
{
// Error - did not insert one row
String err = "insert unable to insert LocalUsage data: " + usg.toString();
Logger.log(err, _MODULE_CLASS, Logger.DEBUG);
throw new DaoException(err);
}
The problem if the query had a foreign key exception, then it will be thrown but it will never get to inside the if. what should I do so that it will get inside the if and output the log I have?
The problem is that this if condition is inside a try catch block, and it is going to the catch and never enters to the if condition.
executeUpdate() might throw an SQLException, as is described in its API documentation. You might want to catch that exception.
int count;
try {
count = ps.executeUpdate();
} catch (SQLException e) {
throw new DaoException("Exception while executing update: " + e.getMessage());
}
if (count != 1) {
// ...
}
As the docs states executeUpdate() may throw an exception so your code flow will fail and you will not be able to do any processing afterwards incase your exception handling is not proper.
Which I think is happening in your code right now.
While doing database call I would suggest you do it like this:
int operationStatus;
try {
operationStatus = ps.executeUpdate();
} catch(SQLException exp) {
final String message = "SQL Exception while calling executeUpdate()";
logger.error(message, exp);
throw new DAOException(message, logger);
} catch(Exception exp) {
final String message = "Exception while calling executeUpdate()";
logger.error(message, exp);
throw new DAOException(message, logger);
} finally {
//you may wish to clean up resources if they are not going to be used after this point.
}
if(operationStatus < 0) {
//Next steps
}