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 !
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();
}
I am working on a basic Java command line email client application. The connector I was provided with will send me emails, however if I "send" an email it will not be located on the connector as I created this email myself. Now when I want to delete an email I can find the folder I am in and delete it by its ID. I also want to delete it from the connector if its located inside the connector so that I will not receive this email again when I refresh emails.
public boolean delete(int messageId) throws IndexOutOfBoundsException
{
if (folders.get(getActiveFolderName()).delete(messageId))
{
if (connector.retrMessage(messageId) != null)
{
connector.markMessageForDeleting(messageId);
//throws exception if not found on connector
}
return true;
}
return false;
}
I tried this, is this a really bad way of going about handling exceptions?:
public boolean delete(int messageId)
{
if (folders.get(getActiveFolderName()).delete(messageId))
{
try{
connector.markMessageForDeleting(messageId);
} catch (IndexOutOfBoundsException e)
{
//this successfully soaks up the exception if its not located in connector
}
return true;
}
return false;
}
Thanks
Though they are considered as bad, as long as you are aware of what's going on and took necessary steps to recover from abnormal behaviour of the program, it will be fine.
I'm just suggesting to you to put at least a log statement.
I would personally not think so. You are using the exception as an indicator of a particular result. You're not trying to hide some error in the code by not doing anything when you catch it. However, I'm not sure if you have the ability to change anything about this connector, but if so, you should adjust it so it isn't throwing errors like that in the first place.
What you're doing is called exception swallowing. It's generally considered bad practice. The risk is to swallow exceptions that might happen when your emails are located in the connector. You don't want that.
You already know a reason to have an IndexOutOfBoundsException, so why not test first if your email is located in the connector?
It is always good practice to log any exception & then can be ignored in the cases like yours.
P.S.: No need to flood the log with stack trace in your case. It can be a simple error message indicating that the exception can be ignored safely.
When handling errors in Java it's common to see the superclasses being the errors that are caugh, such as
Exception, IOException, SocketException, etc.
However how do you go about finding the nitty-gritty details on the exception? How do you single a certain exception type out from the others. For instance, I'm currently working on a small project using Netty.io which throws an IOException for every type of read/write error you can name. This makes sense, because ultimately this is input/output errors, but how would I handle them individually.
Example exceptions:
java.io.IOException: An existing connection was forcibly closed by the remote host
java.io.IOException: Connection reset by peer
java.io.IOException: Stream closed
The list just continues to go on, but how would you go about handling these seperately, one approach that I've found while looking around and seems really nasty is the following.
try {
// ...
} catch (IOException e) {
if(e.getMessage().contains("An existing connection was forcibly closed by the remote host")) {
// Handle error
} else //...
}
This seems very tedious and there's bound to be a better way to do this, a correct way if you will. I've looked through quite a bit of error handling writeups over the last few hours and they all only talk about the big boys that are used commonly. IOException, Exception, SocketException, NullPointerException, and FileNotFoundException. Where I believe SocketException and FileNotFoundException would be directly related to the IOException, more than likely a subclass, correct me if I'm wrong.
Anyway, what's the proper way to go about handling these exceptions and how do you figure out exactly what kind of exception you need to be handling? All I can really do is handle IOException until something more precise comes up, but when developing applications it's always good to be able to handle each error uniquely.
In most of these cases the message is irrelevant from the point of view of your code. It's just something to be shown to the user, or logged. The only salient fact is that the connection is broken, for whatever reason, and there aren't different code paths you can use depending on which message it was.
The only one that's different is 'socket closed', which indicates a coding bug.
EDIT Regarding your comments below:
Any IOException other than SocketTimeoutException on a socket is fatal to the connection.
Invalid packets don't cause IOException: that's an application-layer problem that throws application-layer exceptions, or subclasses of IOException: e.g., java.io.StreamCorruptedException.
There is no such thing as IOException: connection closed by remote host. If the peer closes the connection, that causes an end-of-stream condition, which manifests itself as either read() returning -1, readLine() returning null, or readXXX() throwing EOFException for any other X.
I would suggest catching the exceptions in order, from most specific to least - such that you will notice a circuit break pattern when the exception you are looking for is reached. This is the best I can come up with:
try {
/// Something that can result in IOException or a SocketException
catch (IOException e){
//Do something specific
}catch (SocketExcpetion e){
}catch (Exception e) { //or some superclass of the above exceptions
///
}
Don't forget that you can also catch multiple exceptions of different types using the | command: catch (IOException|SocketException|
The documentation (http://docs.oracle.com/javase/7/docs/api/java/io/IOException.html) contains a long list of direct subclasses. You might want to look through them and check which ones you want to treat differently.
Once you know that, you can use multiple catch-blocks, first the subclasses, then the most general IOException:
catch(SSLException se) {
// do something
}
catch(HttpRetryException he) {
// do something else
}
catch(IOException ioe) {
// nop
}
I'm working on a Thrift server which is basically just a wrapper around the Stanford Parser (although that's not too important). Sometimes the Stanford Parser will throw useful exceptions depending on the input it's given; for instance, if the input is too long (according to the parser), the user generating the input should receive this exception so they can decide how to handle it. However, I can't seem to get Thrift to pass this exception up, and instead only returns
Internal error processing <name of Thrift method being called>
to the client.
I have the following code in that method:
try
{
// a whole bunch of Stanford Parser stuff
}
catch (Exception e)
{
throw new TApplicationException(TApplicationException.INTERNAL_ERROR, e.getMessage());
}
and the method does throw a TApplicationException, but whatever the contents of e.getMessage() are are not being sent to the client. How can I get the exceptions being thrown by the Stanford Parser to be thrown by Thrift to the client?
I am afraid you have to define your own exceptions, instead of using TException or any subclass of it.
That's because Thrift framework wrap your code like this(ProcessFunction.java):
try {
result = getResult(iface, args);
} catch(TException tex) {
LOGGER.error("Internal error processing " + getMethodName(), tex);
TApplicationException x = new TApplicationException(TApplicationException.INTERNAL_ERROR,
"Internal error processing " + getMethodName());
oprot.writeMessageBegin(new TMessage(getMethodName(), TMessageType.EXCEPTION, seqid));
x.write(oprot);
oprot.writeMessageEnd();
oprot.getTransport().flush();
return;
}
So, whatever message you give in TException, will be ignored and replaced by Thrift framework.
Hi i´m development and app with Netbeans Platform and i can´t catch this exception:
org.hibernate.exception.ConstraintViolationException
I use the follow line:
try {
il.delete(lote);
}
catch (HibernateException he) {
NotifyDescriptor error = new NotifyDescriptor.Message(ERROR+he.getMessage(), NotifyDescriptor.ERROR_MESSAGE);
DialogDisplayer.getDefault().notify(error);
}
My interface may throw this exception, and the exception can be captured in the TopComponent. The problem is that I get twice, one is my notification and another from the platform.
How I can fix this?
In case of above code there is no possibility that you will receive exception twice. Because there is only one method call which returns exception.
What might possibility is you might be requesting it two times so that you are receiving exception multiple times.
What you can do is add a log check if method is being called multiple times on single click and fix that issue.