Uncaught java.nio.channels.UnresolvedAddressException - java

With Java 1.7, the following code
try
{
sck = SocketChannel.open();
sck.configureBlocking(false);
sck.connect(new java.net.InetSocketAddress(**<bad remote ip address>**, remote_port));
sel = Selector.open();
...
}
catch (IOException e)
{
return false;
}
doesn't seem to catch the exception if the remote address is a bad DNS (for instance). What did I miss?

The UnresolvedAddressException is not a subclass of IOException, which is why you won't catch it if it's thrown.
UnresolvedAddressException is a subclass of IllegalArgumentException, as shown here, so try catching:
UnresolvedAddressException itself, as it's always better practice to catch the most specific exception type first
Exception if you don't really care about the exception you catch, as you can always halt the program or work around that
Edit: You probably missed that exception because the compiler did not force you to catch it. That is because UnresolvedAddressException is derived from RuntimeException, the type of exceptions which smack you in the head during execution. The exceptions not derived from RuntimeException, such as IOException, have to be caught, which is why your compiler probably told you to wrap your code into a try-catch block in the first place.

UnresolvedAddressException is not a child of IOException.
UnresolvedAddressException extends RuntimeException.
You can try to add catch closure with RuntimeException.

Related

Continue function after error / try - catch

I have a function in a server that sometimes throws an error and seems to crash the server.
Do try-catch blocks prevent servers/program from completly crashing and continue to process? This code handles network requests and I need to make sure the server does not crash and prevent the processing of other network requests to the same function because of an error that occurred and crashed the server.
A common error is a java null pointer exception
EDIT added example pseudo code:
public class myClass{
public static string networkHandler(string s) { //static method
try {
string ss = s;
}
catch(string s) {
//handle error
}
}
}
I am wondering if it is because I need to write another catch block to handle the specific type of error that is crashing the server.
Edit: As answered by #denis, I was wondering if there was a wy to have a catch block of type NullPointerException
A try catch allows you to catch an error (that will stop your program from completely crashing) and you can then handle the error. However something like a NullPointerException typically indicates an error in your code.
There's some more info on exception handling here: https://docs.oracle.com/javase/tutorial/essential/exceptions/handling.html
Depending on your server environment and frameworks you should have a global exception handling strategy. Local try-catches can only prevent crashes to that specific exceptions on that specific location.
Furthermore, null pointed exceptions are signs of code and algorithms issues so better seek the root cause and fix it
If the NullPointerException is your culprit then catch an exception like this
try {
// code that throws null pointer excpetion that crashes the server
}
catch(NullPointerExcpetion npe) {
//handle error
}
It should prevent server from crashing from this specific exception.
So, you want to use try-catch and you are using it wrong in your pseudocode.
try {
string ss = s;
}catch(string s) {
//handle error
}
you are passing an string to catch which is wrong. you should pass an exception that you want to be catched. in this case NullPointerException, so you can rewrite it like :
try {
string ss = s;
}catch(NullPointerException ex) {
//handle error
}
you can read this link for more information about try-catch-finally structure in java.

Does it make a difference if I close the database connection after try/catch rather than in finally

In following two examples, I am 1) closing the database in the finally block and 2) closing it after the try ... catch. Does it make a difference which approach is used? If no, what is the point of finally, as we can release resources without using it?
try{
// initialise a database connection
} catch (Exception e) {
e.printStackTrace();
} finally{
db.close
}
Second
try{
// initialise a database connection
} catch (Exception e) {
e.printStackTrace();
}
db.close
One way to explain why finally is better / necessary is to point out the flaws in this version of the code:
try {
// initialise a database
} catch (Exception e) {
e.printStackTrace();
}
db.close();
The first problem is that if some exception that is a subtype of Error is thrown, then the try ... catch won't catch it. Error is a subtype of Throwable but not of Exception.
You might counter that one should not attempt to recover from an Error exception. That is true in many contexts, but not in others. For example, if this code was executed in a worker thread, a lot of frameworks will try to create a new thread to replace the one that died. That would result in the database handle leaking.
The second problem is that you are catching and squashing exceptions. Indeed, for the code as you have written it, you have to do this for the db.close() at the end to be executed. This might work in your example, but it won't work in general. For instance, what if you need to return something from this code ... or allow the exception to propagate for the caller to deal with.
The third problem is that you are catching Exception so that you can close db.close() in all cases. However, by doing this, you are most likely catching exceptions that should not be caught at this level. For example, if something withing the try block throws an NPE, you should not "squash and recover". Instead, you should allow the exception to propagate.
Note that using finally means that you don't have to worry about leakage in the case of Errors, recovering when you don't want to, or catching more exceptions than you mean to.
Now you can attempt to work around the three problems above without using finally, but it introduces other problems. (For example you could catch and then rethrow Exception with a db.close() in the handler, but then you would typically need to declare the enclosing method as throws Exception!)
Note that calling printStackTrace() like that is not advisable. A better approach is to use a logging framework ... so that the error reporting can be managed via a configuration file.
Finally, the block is a safe point to close the resource as finally block will execute in every situation until the System#exit called. It may happen that catch is also thrown an exception, in that case, your resource will not close if you put outside after catch block.
It seems to me that the question is what is the difference between closing the database connection in the finally block versus after the finally block.
I will assume that the database was opened INSIDE the try block. If the code inside the try block threw an exception and your closed the database only after the finally block, you won't close the database when the exception is handled.
The correct way to do this is to close the database in the finally block. The finally block will run unconditionally, whether an exception was thrown or not.
Consider a little more specific example:
try{
// initialise a database
} catch (SocketException e) {
e.printStackTrace();
} finally{
db.close
}
This will cleanup even if the exception was not a SocketException.
try{
// initialise a database
} catch (SocketException e) {
e.printStackTrace();
}
db.close
This won't. It will just bubble up the exception.
(I chose SocketException randomly. This of course goes as well for other Exceptions, Throwables etc)
Baseline: Using the finally block to perform clean-up fortifies your code against unexpected exceptions and exceptions thrown in your catch-blocks.

What is the right way to deal with terminated socket "client"

I have socket serve/client application. The "server" is waiting for data from "client", but if the client had been terminated the server throws EOFException.
Somewhere in the code in the server socket I have:
private ObjectInputStream in;
and somewhere I read the data:
in.readObject();
So should I just surround in.readObject(); in try-catch block or there is another solution?
If you look in the Javadoc API for ObjectInputStream.readObject, you'll see the list of exceptions
ClassNotFoundException - Class of a serialized object cannot be
found.
InvalidClassException Something is wrong with a class used by
serialization.
StreamCorruptedException Control information in the stream is inconsistent.
OptionalDataException Primitive data was found in the stream instead of objects.
IOException - Any of the usual Input/Output related exceptions.
IOException (which 99% of the time is a SocketException (subclass of IOException) is special case where your Socket has shutdown, so you should process this as if you have lost connection.
All of the other exceptions however indicate that your client is sending you something you aren't expecting. You should catch each of these Exceptions by name and send back a message saying that they need to update the client software version to the version that your server is ready to communicate with. Flush that message out, and then probably best to close the socket.
You can use like following. EOFException is a direct subclass of IOException. You should also catch IOException.
try{
....
in.readObject();
....
} catch(EOFException ex1){
// eof exception is thrown
} catch(IOException ex2){
// other types of IO exception is thrown
}

Exceptions in Java (Recoverable vs Fatal)

I have a java program that tries to collect a certain rss feed from a list of servers. If there are any failures, (authentication, connection, etc) I want to throw an exception that basically takes me back to the main loop where I can catch it, display some info in the logs, and then move on the trying the next server in the loop. Most exceptions seem to be fatal though... even when they don't really need to be. I beleive I have seen exceptions that are not fatal... but don't remember for sure. I have tried to search around but I am probably using the wrong terminology.
Can someone help me get pointed in the right direction here? Are there particular types of exceptions I can throw that will be recoverable vs stopping the entire program in its tracks?
No Exception needs to be fatal. (Errors however, are meant to be fatal. Don't catch them.) All you have to do is catch the Exception somewhere, and it's not fatal.
try
{
riskyMethod();
}
catch (ReallyScaryApparentlyFatalException e)
{
log(e);
// It's not fatal!
}
There are no "unrecoverable exceptions" per se. In Java, if it registers as an "exception" you can catch it:
try {
// Attempt to open a server port
} catch (SecurityException ex) {
// You must not be able to open the port
} catch (Exception ex) {
// Something else terrible happened.
} catch (Throwable th) {
// Something *really* terrible happened.
}
What you may want, if you are creating a server connecting application, something like this:
for(Server server : servers) {
try {
// server.connectToTheServer();
// Do stuff with the connection
} catch (Throwable th) {
//Log the error and move along.
}
}
Error:
An Error "indicates serious problems that a reasonable application
should not try to catch."
Exception:
An Exception "indicates conditions that a reasonable application might
want to catch."
Exceptions are always meant to be recoverable, no matter checked or unchecked though it is possible always not to handle them, but it should be. while On the
other hand, error must be fatal. However, even error can be handled, but it would rather be just fancy way to say "it's a crash"
probably you would wanna have a look at Exception vs Error
Whatever the type of the exception you throw, it will go up the call stack until it's caught. So you just need to catch it:
for (Server server : servers) {
try {
contactServer(server);
}
catch (MyCustomException e) {
System.out.println("problem in contacting this server. Let's continue with the other ones");
}
}
Read the Java tutorial about exceptions.

java rmi server side exception handling

Do you see any possibility to log server side exceptions?Consider such code on the server side:
catch (Exception ex) {
throw new IllegalStateException (ex);
}
The exception is caused by the client-side call. Of course, exception will be noticed on the client-side. Is there any way to somehow handle it on the server side, without catch runtime exceptions? Some kind of handler that would allow me for example to log the stacktrace of the exception?
Any ideas?
you can wrap your server instance in a java.lang.reflect.Proxy and implement your server-side logging in the proxy. just make sure the proxy is exported, not the server implementation.
Commonly, the top level server method will have throws Exception.
If you wrap your "do it" code in this method with a try-catch Exception, and you can log it there as still throw it.
public Response myServerTopLevelMethod() throws Exception {
try {
myImplCode();
catch (Exception e) {
Log.error(e);
throw e;
}
}
Now you have some options about what to do. The basic options are:
You can just re-throw the Exception (as above)
You can play nice and return a "something bad happened" response - like many web servers do
Here's an example of option 2:
public Response myServerTopLevelMethod() throws Exception {
try {
myImplCode();
catch (Exception e) {
Log.error(e);
return new Response("Yikes! Something exploded... we'll look into it.");
}
}
Incidentally, the "Log + throw" of option 1 is one of the few times that you ever want to do this; at the top level method. At other times you should generally either log or throw, not both.
There are RMI system properties that will automatically log server-side exceptions for you. See the links on the RMI Home Page.

Categories