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.
Related
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.
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.
I wonder how to handle exceptions correctly within a client server application. My client sends an information to the server(thread) which receives it within its run method.
I have already read something about uncaught exception handling when dealing with exceptions in the run method but want to know if this is the correct way to do it in my case.
I want to catch the exception on the client side.
I have in mind to do the following:
//Server
run(){
try{
...
}
catch(Exception e){
clientoutputstream.write(...); //transmitting the error
}
}
Any other suggestions?
You should put a try { } catch (IOException) around your read() call so you know if the other end has closed the connection. The other thing you might want to do is to put a try { } catch(Throwable) { } around the processing code so you can manually close the socket (Be very careful about catching Throwable) But if you just let the thread die the Socket will be closed when the object is garbage collected or when it times out
Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 9 years ago.
Improve this question
Im new to Java here, so I was only guessing while working here.
I had some code
try {
sendMailWithAttachment();
} catch (AddressException e) {
e.printStackTrace();
sendMailWithoutAttachment();
} catch (MessagingException e) {
e.printStackTrace();
sendMailWithoutAttachment();
}
But the "catch" code was never executed, so I suspected there is another type of exception that Im not catching, and instead of guessing what it was, I decided to catch some "general" kind of exception, and I blindly tried this
try {
sendMailWithAttachment
} catch (AddressException e) {
e.printStackTrace();
sendMailWithoutAttachment();
} catch (MessagingException e) {
e.printStackTrace();
sendMailWithoutAttachment();
} catch (Exception e) {
e.printStackTrace();
sendMailWithoutAttachment();
}
And then my catch code was suddenly ran.
What have I actually done here, and most importantly:
Can I always catch a general exception, just in case?
All exceptions subclass the Exception class. So, what you have done is said, "If an AddressException happens, handle it like this; if a MessagingException happens, handle it like this; for any other Exception, handle it like this."
In your case, all three catch blocks are identical, so you CAN just use your catch (Exception e) { ... } block, but this is considered poor coding. Typically, you should know which exceptions your code might throw and handle each of those exceptions appropriately.
Catching a general Exception is always possible, though usually not a good practice.
Many times, a component cannot handle the exception, and there is really no point on catching it, and the 'upper levels' should handle it.
It also might create security risks (you don't want to display what went wrong in the program, you rather log it and send it to the dev team).
Notes:
Catching Exception will catch all exceptions which are extending Exception, but it won't catch all Throwables (like Error).
In your code, what happens if the catch block itself throws an exception? usually the exception handling should be very minimal, in your case, I'd try to verify before checking if sending mail with attachment is possible, and not only on the exception (if it can be done).
There is no point in catching multiple 'types' of exceptions and finally with Exception if the handling is the same, just catch Exception without the rest in this case.
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.