Java(FX) Fail-Safe Alert on Faulty Termination / Crash? - java

I absolutely need my programme to exit cleanly, i.e. if and only if the user does it manually. In any other case, my programme must notify them either by means of displaying a popup or, better yet, playing a sound (on loop).
Hence: is there a fool-proof, fail-safe way for me to alert the user that something has gone wrong? Even if the exception already occurrs in JavaFX's Application#start method? I was experimenting with shutdown hooks, but the general consensus here on SO is that they are not meant for such heavy operations.

What you could do is surround parts of your program with try catch statements. That way when an error occurs you can create a pop-up in the catch statement. The other solution is the throws exception however that will not allow you to create a pop up notifying the user upon an error.

Related

How to deal with: Call to 'Thread.sleep()' in a loop, probably busy-waiting

Guys how to deal with such code and warning?
private void listenOnLogForResult() {
String logs = "";
int timeCounter = 1;
while (logs.isEmpty()) {
try {
timeCounter++;
Thread.sleep(2000); // Wait 2 seconds
} catch (InterruptedException e) {
log.error(e.getLocalizedMessage(), e);
}
if (timeCounter < 30) {
logs = checkLogs()
} else {
logs = "Time out";
}
}
}
I need to pause current thread for 2 seconds to wait file to be filled, but my Intelij Rise an issue here.
And also I am getting error from sonar:
SonarLint: Either re-interrupt this method or rethrow the "InterruptedException".
I've tried already with many ExecutorService, but it is always run in seperate thread, and I need to pause current one.
Please help..
The busy-waiting warning
This is a warning coming from intellij that is dubious, in the sense that what you're doing is often just straight up required. In other words, it is detecting a pattern that is overused, but whose usage cannot be reduced to 0. So, likely the right solution is to just tell intellij to shut up about it here.
The problem it is looking at is not that Thread.sleep. That is not the problem. However, intellij's detector of this pattern needs it to find this case, but it is not what it is complaining about, which might be a little hard to wrap your head around.
What IntelliJ is worried about, is that you're wasting cycles continually rechecking log.isEmpty() for no reason. It has a problem with the while aspect of this code, not the sleep. It would prefer to see code where you invoke some sort of logs.poll() method which will just wait until it is actively woken up by the act of new logs appearing.
If this is all running within a single java process, then you can indeed rewrite this entire system (which includes rewrites to whatever log is here, and a complete re-imagining of the checkLogs() method: Instead of going out and checking, whatever is making logs needs to wake up this code instead.
If it's not, it is likely that you need to tell intellij to shut it: What you are doing is unavoidable without a complete systems redesign.
The re-interrupt warning
You have some deplorable exception handling here.
Your exception handling in general
Do not write catch blocks that log something and keep moving. This is really bad error handling: The system's variables and fields are now in an unknown state (you just caught and logged some stuff: Surely that means you have no idea what conditions have occurred to cause this line of execution to happen!), and yet code will move right along. It is extremely likely that 'catch exceptions and just keep going' style code results in more exceptions down the line: Generally, code that operates on unknown state is going to crash and burn sooner rather than later.
Then, if that crash-and-burn is dealt with in the same fashion (catch it, log it, keep going), then you get another crash-and-burn. You end up with code that will, upon hitting a problem, print 186 exceptions to the log and they are all utterly irrelevant except the first one. That's bad yuyu.
You're also making it completely impossible for calling code to recover. The point of exceptions is that they need to bubble upwards endlessly: Either the exception is caught by code that actually knows how to deal with the problem (and logging it is not dealing with it!), which you are making impossible, or, the code exception should bubble up all the way to the entry-point handler which is the right place to log the error and abort the entry-point handler.
An entry-point handler is a generic module or application runner; out of the box, the code baked into java.exe itself that ends up invoking your psv main() method is the most obvious 'entry point runner', but there's more: Web frameworks will eventually invoke some code of yours that is supposed to handle a web request: That code of yours is analogous to psv main(): It is the entry-point, and the code in the web framework that invokes it, is the entry-point runner.
Entry-point runners have a good reason to catch (Throwable t), and to spend their catch block primarily logging it, though they should generally log a lot more than just the exception (a web handler should for example log the request details, such as which HTTP params were sent and which path request it was, maybe the headers, etc). Any other code should never do this, though.
If you have no idea what to do and don't want to think about what that exception might mean, the correct 'whatever, just compile already javac' code strategy is to add the exception type to your throws line. If that is not feasible, the right code in the catch block is:
} catch (ExceptionIDoNotWantToThinkAboutRightNow e) {
throw new RuntimeException("Uncaught", e);
}
This will ensure that code will not just merrily continue onwards, operating on unknown state, and will ensure you get complete details in logs, and ensures that calling code can catch and deal with it if it can, and ensures that any custom logging info such as the HTTP request details get a chance to make it to the logs. Win-win-win-win.
This case in particular: What does InterruptedEx mean?
When some code running in that java process invokes yourThread.interrupt(), that is how InterruptedException can happen, and it cannot possibly happen in any other way. If the user hits CTRL+C, or goes into task manager and clicks 'end process', or if your android phone decides it is time for your app to get out as the memory is needed for something else - none of those cases can possibly result in InterruptedExceptions. Your threads just get killed midstep by java (if you want to act on shutdowns, use Runtime.getRuntime().addShutdownHook). The only way is for some code to call .interrupt(), and nothing in the core libs is going to do that. Thus, InterruptedException means whatever you think 'call .interrupt() on this thread' means. It is up to you.
The most common definition is effectively 'I ask you to stop': Just shut down the thread nicely. Generally it is bad to try to shut down threads nicely if you want to exit the entire VM (just invoke System.shutdown - you already need to deal with users hitting CTRL+C, why write shutdown code twice in different ways?) - but sometimes you just want one thread to stop. So, usually the best code to put in a catch (InterruptedException e) block is just return; and nothing else. Don't log anything: The 'interrupt' is intentional: You wrote it. Most likely that is nowhere in your code base and the InterruptedException is moot: It won't ever happen.
In your specific code, what happens if your code decides to stop the logger thread is that the logger thread will log something to the error logs, and will then shortcut its 2 second wait period to immediately check the logs, and then just keeps going. That sounds completely useless.
But, it means whatever you want it to. If you want an ability for e.g. the user to hit a 'force check the logs right now' button, then you can define that interrupting the logging thread just shortcuts the 2 seconds (but then just have an empty catch block with a comment explaining that this is how you designed it, obviously don't log it). If you ALSO want a button to 'stop the logging thread', have an AtomicBoolean that tracks 'running' state: When the 'stop log-refreshes' button is hit, set the AB to 'false' and then interrupt the thread: Then the code you pasted needs to check the AB and return; to close the thread if it is false.
fun sleep(timeMillis: Long) {
val currentTimeMillis = System.currentTimeMillis()
while (true) {
if (System.currentTimeMillis() - currentTimeMillis >= timeMillis) {
break
}
}
}
and use this in your method(It's code by koltin,you should trans to java)

What's the point of try/catch blocks to catch Exceptions?

Why do we need try/catch blocks to catch any Exceptions that may arise in our code? Once we run the program and lets assume we have a RuntimeException, won't the program just automatically abort and give us the error anyways? Why do we need try/catch blocks to do this for us then?
It's just good practice. If the user is given with something like "IndexOutOfrangeexception" what is he going to do with it? Just assume everything is OK and he should start over? What in case of doing some work with the software - is the work lost? What happened?
Put yourself in such stuation: you downloaded some software, you start using it as normal, and you are happy with it. But one day you run program and it gives you error and program dies - do you know what happened? No. Do you know what went wrong? No. Do you know how to prevent it and start using software so the error doesn't occur again? No.
YOU ARE THE DEVELOPER, you know what happens inside. So for example, you are trying to save data in database, but somehow connection got lost and you will likely get an exception - in catch block you can catch this exception and give the user MEANINGFUL information, e.g. "The connection with database is lost. Check the network. Your data is not saved and you should do the work again." - isn't that better than just some "SQL exception" alongside with the stacktrace?
Additionally, catch/finally blocks are here to clean-up potential mess, for example you are writing some content to a file, but it only makes sense, when you can write all data, not just the part of it. So in catch block you could erase incomplete data, so the file is not corrupted for example.
Also, when working with unanaged resources, you should use finally block to clean them up (for example DB/netowrk connections).
Think about the scenarios when working with a live website or application. You wouldn't want the user to see a blank screen or a screen full of error trace code. In such scenarios, potential areas of exception can be handled to show a message to the user that makes sense "sorry, you are exceeding more than 10 items in your cart etc ", "you do not have sufficient amount in your account", "username cannot have symbols ", "out service us un-operational right now please come back later".
Try catch is used to handle the such error conditions gracefully. You can enclose a code set into try and its catch would be responsible to handle it. Handling may depend on your use case but your java program wont terminate.
Abrupt termination of program doesn't let you know the actual reason of failure.
Because if you don't catch an exception the entire method execution will simply stop, including the execution of any calling methods. So if a method A needs something of method B and calls it, and method B throws an exception, then that exception will cause method A to stop execution. If method A was being called by another method that method will stop execution too if it doesn't catch the exception from method B. So an exception will work its way up the method calling chain until it is catched by a method or gets to the most upper/outer method.
Also, any exception that is not inheriting from the RuntimeException class or is not an instance of the RuntimeException class itself must either be catched or else your code will not compile. If you really don't want to handle this kind of exception then you can also let the calling method receive the exception by adding throws Exception to your method signature. A runtimeexception extending class is called an unchecked exception, you don't have to include that in the method or in the method signature. Anything extending Exception but not RuntimeException is called a checked exception and should either be catched or put in the method signature by using throws keyword.
EDIT: Here you can find a good explanation too Does every exception have an required try-catch?
Other than examples users given, also, on Android for hardware specific operations, camera for instance, can throw RuntimeExceptions even you do everything right, it does it a lot with camera based on devices. I set ISO for instance camera and it's not a crucial for my app to work but i don't want my app to crash so i throw an exception and show a warning to user so app continue to work.

How do I prevent an exception from stopping my program?

I'm using a thread to run a half of an application, and the other half is running by itself. I did this so that the one part fetching the data (because I'm running an infinite loop) would not stop the other part from doing it's job. Now I was wondering: if an exception occurred on one part it would block the some of the other part because they are dependent on each other.
So my question is, how could I prevent an exception from stopping my whole program and make it continue do things?
Try-catch or throw an exception. If neither of those sound familiar, I would look them up.
an example of try-catch
try
{
//your code that may throw exception
}catch(TheException e){
e.printStackTrace(); // or however you handle exceptions
}
good resource for throwing exceptions: https://docs.oracle.com/javase/tutorial/essential/exceptions/throwing.html
Throwing an exception from one thread generally will not impact the runtime of the others. Threads are kind of off in their own little world in that regard.
That said, if two threads are sharing some state (whether directly through the heap or indirectly through a database or something like that) and one thread leaves the application's data in an unstable/corrupted state because it bombed out, that could obviously impact the behavior of the other threads, making them do further "bad stuff." You will want to prevent this whenever possible; best way to do it is to document your exceptions as best you can and to catch and handle them when thrown, and to back your logic with robust unit tests.
You can create a boolean variable maybe called running so that while your while loop is working fine, this variable will be true. Immediately an exception is caught, the variable becomes false. Your main task can then check the variable anytime it wants to use the shared data. If the variable is true, read the data; else, do something else like restarting the thread depending on the type of exception caught.
Remember, in order to make the variable false, you will need to include its update in your catch clause.
There are better and more complex methods out there like the use of ExecutorService.

Continual Check for Pop Up in QTP

I have an error window that pops up every once in a while when my application is running. It is a Java Swing application and the error is displayed when an exception is caught, but not necessarily handled in a way that can be fixed. For example handling an exception that can be fixed would be like if I divided by zero I would be able to catch an ArithmeticException and display a box that says something like "You tried to divide by zero, please try again..."
The error that I'm receiving is due to a try..catch block catching ANY exception, but the exception is just some Java exception that the user would know nothing about so then telling the END USER (QTP in this case) that an "unexpected error" occurred. The application has been under development for a couple years now so it is terribly complex and there is no way that QTP can handle these errors unless I literally add some CheckForUnexpectedError function that is called every other line of the script. Is there any way to make some sort of function that is constantly running in the background checking if this particular error window pops up? If the window pops up the test should fail, but I have no way of predicting when the window will pop up, and thus, I can't handle it in QTP and my script just gets stuck unless I have that way to constantly check for it in the background.
It has been a long time since i touched QTP so the feature may no longer exist but there used to be a feature called recovery scenarios. This feature would basically be a set of scripts that could run when qtp hit an error to see if it could recover. You could make a recovery scenario to dismiss this popup and it would continue back on from where it left off.
EDIT
http://www.tutorialspoint.com/qtp/qtp_recovery_scenarios.htm

When is it OK to catch a RuntimeException

On a recent project I recommended catching a RuntimeException within a test harness code and logging it. The code processes a series of inputs from a database, and I do not want the test to stop due to failure of any one input (Null values, Illegal arguments, etc.). Needless to say, my suggestion triggered a passionate discussion.
Is catching any kind of RuntimeException acceptable? If yes, what are other scenarios where it is OK to catch RuntimeExceptions?
You catch RuntimeException for the same reason that you catch any exception: You plan to do something with it. Perhaps you can correct whatever caused the exception. Perhaps you simply want to re-throw with a different exception type.
Catching and ignoring any exception, however, is extremely bad practice.
Unless you can correct a RuntimeException, you don't want to catch it...
...only true from a developers point of view....
you have to catch all exceptions before they reach up to the UI and make your user sad. This means on the "highest level" you want to catch anything that happend further down. Then you can let the user know there was a problem and at the same time take measures to inform the developers, like sending out alarm mails or whatever...
It is basically considered a data/programming error that could not be forseen, thus you want to improve future releases of the software while at the same time take the user by the hand and move on in a controlled manner...
RuntimeException is intended to be used for programmer errors. As such it should never be caught. There are a few cases where it should be:
you are calling code that comes from a 3rd party where you do not have control over when they throw exception. I would argue that you should do this on a case by case basis and wrap the usage of the 3rd party code within your own classes so you can pass back non-runtime exceptions.
your program cannot crash and leave a stack trace for the user to see. In this case it should go around main and around any threads and event handling code. The program should probably exit when such exception occurs as well.
In your specific case I would have to question why you are having RuntimeExceptions occur in the tests - you should be fixing them instead of working around them.
So you should guarantee that your code only throws RuntimeExceptions when you want to have the program exit. You should only catch RuntimeExceptions when you want to log it and exit. That is what is in line with the intent of RuntimeExceptions.
You can look at this discussion for some other reasons that people give... I personally haven't found a compelling reason in the answers though.
In my code 99% of my exceptions are derived from runtime_exception.
The reasons I catch exceptions are:
Catch Log and Fix problem.
Catch Log and Generate a more specific exception and throw
Catch Log and rethrow.
Catch Log and Kill operation (discard exception)
User/request initiated action fails.
An HTTP request handler for example. I would rather the requested operation die rather than bring the Service down. (Though preferably the handler has enough sense to return a 500 error code.)
Test case passed/failed with an exception.
All exceptions not in the main thread.
Allowing exceptions to escape a thread is usually badly documented but usually causes program termination (without stack unwinding).
Years ago, we wrote a control system framework and the Agent objects caught runtime exceptions, logged them if they could and continued.
Yes we caught Runtime exceptions including OutOfMemory in our framework code( and forced a GC, and it's surprising how well that kept even quite leaky code running.)
We had code that was doing very mathematical things involving the real world; and from time to time a Not-A-Number would get in due to tiny rounding errors and it coped okay with that too.
So in framework / "must not exit" code I think it can be justifiable. And when it works it's pretty cool.
The code was pretty solid, but it ran hardware, and hardware tends to give screwy answers sometimes.
It was designed to run without human intervention for months at a time.
It worked extremely well in our tests.
As part of the error recovery code, it could resort to rebooting the entire building using the UPS's ability to turn off in N minutes and turn on in M minutes.
Sometimes hardware faults need to power cycled :)
If I remember, the last resort after an unsuccessful power cycle was it sending an email to it's owners, saying
"I tried to fix myself and I can't; the problem is in subsystem XYZ", and included a link to raise a support call back to us.
Sadly the project got canned before it could become self aware :)>
Personally, I've always been told that you want to catch all RuntimeExceptions; however, you also want to do something about the exception, such as running a failsafe or possibly just informing the user that an error occurred.
The last Java project that I worked on had a similar approach, at the very least, we would log the exception so that if a user called complaining about a bug, we could find out exactly what happened and see where the error occurred.
Edit 1: As kdgregory said, catching and ignoring are two different things, generally, people are opposed to the latter :-)
We all know that checked exceptions and RuntimeExceptions are the two categories of exceptions. It is always suggested that we handle (either try-catch or throw) the checked exceptions because they are the programming conditions where unfortunately programmer can not to do anything on its own;
Like FileNotFoundException it is not the programmer who puts files on user's drive if program is actually trying to read the file 1.txt which is supposed to be there on f:\ of user with the statements:
File f11 = new File("f:\\1.txt");
FileInputStream fos = new FileInputStream(f11);
If the file is found it's all ok, but what happens in the other case if the file is not found is that, program crashes down with 0 error from the user. In this scenario programmer did not do anything wrong. This could be a checked exception which must be caught for the program to continue running.
Let me also explain the second scenario with which the concept of RuntimeException will be clear. Consider following code:
int a = {1,2,3,4,5};
System.out.println(a[9]);
This is poor coding which generates the ArrayIndexOutOfBoundsException. Which is an example of RuntimeException. So programmer should not actually handle the exception, let it crash the program, and later fix the logic.
You catch RuntimeException when you want to process it. Maybe you want to rethrow it as a different exception or log it to a file or database, or you want to turn on some exception flag in the return type, etc.
You catch RuntimeExceptions (in any language: unexpected exceptions/“all” exceptions) when your program is doing multiple subtasks and it makes sense to complete every one you can rather than stopping on the first unexpected situation. A test suite is a fine situation to do this — you want to know which of all the tests failed, not just the first test. The key characteristic is that each test is independent of all the others — it doesn't matter whether a previous test doesn't run because the order is not significant anyway.
Another common situation is a server; you don’t want to shut down just because one request was malformed in a way you didn't expect. (Unless it’s really, really important to minimize the chances of inconsistent state.)
In any of these situations, the appropriate thing to do is log/report the exception and continue with the remaining tasks.
One could vaguely generalize to any exception: it is “appropriate to catch” an exception if and only if there is something sensible to do after catching it: how your program should continue.
If a client can reasonably be expected to recover from an exception, make it a checked exception.
If a client cannot do anything to recover from the exception, make it an unchecked exception.
Here's the bottom line guideline.
From Java Docs. Please read this Unchecked Exceptions — The Controversy

Categories