I'm stuck in the middle of a real headscratcher here. My program gets to a point where it's supposed to throw an Exception and have it caught by it's parent process, except somewhere in there, the Thread seems to simply stop functioning and I can't explain why.
My program is very complex, but here is the essence of my problem {
public class ClassOne {
public CustomClass computeCustomClass() throws IOException {
//CustomClass is an elsewhere defined valid class in my code.
try {
//The core code of this "computeCustomClass" operation has the
//potential of throwing a "CustomException", an Exception class
//of my own creation.
} catch (CustomException e){
//I have inserted a logging utility here and it is logging that
//this "catch" process is definitely being executed.
//I will now wrap the CustomException in an IOException, as the
//core code of "createCustomClass()" has the potential to generate
//it's own IOExceptions, and the handling of a CustomException should
//be done just the same by a parent process as if an IOException had
//occurred.
throw new IOException(e);
}
}
}
public class ClassTwo {
private ClassOne myObject;
public void processData(){
try{
//I've inserted a logging code here to track when this line is
//executed.
CustomClass data = myObject.computeCustomClass();
//Another bit of logging code goes here and records when the
//"computeCustomClass()" request goes off without a hitch.
// Code goes here that processes the "data" variable;
} catch (IOException e){
//There is logging code here, but it NEVER records this "catch"
//section being executed! Even when the "CustomException" catcher
//in ClassOne.computeCustomClass() is logged as having executed!
//It's as if the thread running this code abruptly stops without
//throwing any exceptions/errors or any indication as to what's
//occurred!
}
}
}
To make matters all the more confusing, I have another thread that runs concurrently to the one that executes the above code. One of this second thread's jobs is to post regular logs about the other thread. Even after whatever occurs that prevents the "catch IOException" code from executing, the thread that SHOULD be executing it reports a "true" value for "isAlive()", and a "false" value for "isInterrupted()".
I don't know what's happening. Any ideas why it might be stalling here, or can somebody suggest a way of diagnosing what the failure actually is?
I see from grepCode that constructing an exception with a cause actually calls the toString() method on the cause.
If your custom exception has a toString() method that could throw an exception or cause some significant time delay then this could be a source of your problem.
You could also - temporarily - use:
//} catch (IOException e){
} catch (Throwable e){
just in case you catch block is being bypassed.
Related
I have a static method used to get the title from a PDF using the metadata via itext, which is used as a small part of a major Task.
I noticed an inexplicable path that I narrowed down to this section of code. Specifically, in the line where I instantiate a PdfReader, the process doesn't throw an exception or continue through to the print statement. In fact, it clears out all of my for loops up to the top level of my program and acts as if nothing has happened and my task completed.
try {
System.out.println("Entered method");
PdfReader myReader = new PdfReader(file.getAbsolutePath());
System.out.println("Reader instantiated"); //if no issues, prints to console
Map<String, String> info = myReader.getInfo();
System.out.println(info.get("Title"));
return info.get("Title");
} catch (IOException e) {
System.out.println("PdfReader throws exception"); //if issues, prints to console
e.printStackTrace();
}
Unless I'm mistaken, when this set of code is executed in my method, either "Reader Instantiated" or "PdfReader throws exception" is printed out to the console.
Neither happens. Instead, the process skips every if/for/while loop it is currently in and ends the task.
I'm wondering if someone can explain to me what is happening and how I should go about fixing it?
In the odd event this is searched for, yes, catching Throwable stops the thread from bailing out. I had never seen something like this before. The cause behind the problem was that a PDF was password-protected, so getInfo() failed.
Suppose I want to have an unchecked exception for a specific "case" in my code--
say when a queue is 75% full. All I need is an Exception saying "queue has reached the 75% threshold".
One-- the most obvious(?) way of doing this is
public class QueueT extends RuntimeException {
QueueT () {
super("queue has reached the 75% threshold");
}
}
All&only use I have for this exception is
try {
// some stuff here
throw new QueueT();
} catch (QueueT e) {
System.out.print("<<"+e+">>");
}
what I'm wondering is-- what exactly i'm gaining by going with the above-- writing an exception--
rather than the below. Recall: i have no other use-- won't be needing those other methods of Throwable or anything else.
try {
// some stuff here
throw new RuntimeException("queue has reached the 75% threshold");
} catch (RuntimeException e) {
System.out.print("<<"+e+">>");
}
From what i see, the only gain i have is the comfort of calling the constructor without bothering a String attribute.
It's even gainful-- i can easily parameterize the threshold that i'll throw the exception on:
// setting the percentage value here
throw new RuntimeException("queue has reached the" + percentage + "% threshold");
Thanks in advance.
Suppose I want to have an unchecked exception for a specific "case" in my code-- say when a queue is 75% full. All I need is an Exception saying "queue has reached the 75% threshold".
This is a poor case for exceptions. Exceptions are not used for business logic; they are used for exceptional conditions. This seems to be an expected scenario and more like a notification than an exception. How would you expect a person who catches this exception to react? Just ignore it? If so, what is the purpose of the exception? Also, using exceptions in this manner is not performant at all since it has to fill in the stack trace, and doing this repeatedly will make your performance very bad.
As to your other question, the benefit of using your own runtime exception versus RuntimeException is that you now have your own exception that is (hopefully) semantically appropriate, which you can throw or handle appropriately. Simply using RuntimeException by itself doesn't really give that much information.
What you gain is that in your first example,
try {
// some stuff here
throw new QueueT();
} catch (RuntimeException e) {
System.out.print("<<"+e+">>");
}
if you replace catch (RuntimeException e) with catch (QueueTe):
try {
// some stuff here
throw new QueueT();
} catch (QueueTe e) {
System.out.print("<<"+e+">>");
}
Here, you can very exactly say what type of error to catch. Otherwise, you may have another part of your code throw a run time exception and your code to deal with a nearly full queue may try to be applied to an exception totally unrelated to the queue. If you only catch the QueueT exception, you can apply code better and more exactly.
The interest of the first call is easy to understand if you change a bit the catch clause :
try {
// some stuff here
throw new QueueT();
} catch (QueueT e) {
System.out.print("<<"+e+">>");
}
So you will only catch instance of QueueT instead of potential others runtimes like null pointer, such kind of exception you would better let propagate to the entry point in order to detect some coding or design issue.
In Fact in the code you wrote first, you won't be able to differentiate the expected full queue case from a real runtime error. You will lost the error information and the program will act as if the queue were full whereas it isn't
A good practice is to never catch the exception super type, neither runtime nor throwable (the worst one).
Another one is to name an exception with the exception suffix : QueueAboutFullException for example.
Another one is not to use programming by exception if the place you catch the exception is about the same than the one where you throw it. Prefer a simple if because it cost much less than the interruption
If I have a try block that throws a RuntimException subclass, can a subsequent catch block catches it as an Exception? Specifically:
public class MyAppException extends RuntimeException {
// ....
}
// In some other part of the code:
try {
// Executing this results with doSomething() throwing a MyAppException.
int x = doSomething();
} catch(Exception exc) {
// Does the thrown MyAppException get caught here?
}
My thinking is yes, because a RuntimeException extends Exception. However I have some production code that is not behaving this way. So obviously, if the answer is no, then that's my answer; otherwise I need to dig down and see why my code is breaking bad. Thanks in advance!
RuntimeException is derived from Exception, so it will get caught.
Having said this, don't do it! Runtime exceptions should be prevented, not caught.
Yes. It will catch RuntimeExceptionbut in case any Exception arise in catch block that you have to catch again.
I would suggest you to make a local deployment and debug the code.
If catch(Exception) is not catching your RuntimeException then your application is not behaving the way you think.
try {
throw new RuntimeException();
} catch (Exception e) {
System.out.println("Caught "+e);
}
prints
Caught java.lang.RuntimeException
Yes. It is possible to catch RuntimeExceptions.
All subclasses of Throwable can be caught.
Yes , you can catch RuntimeException...But i think its not a good approach, if you catch it you should properly manage it. Otherwise the result is out of your hand. Best way is to leave it to JVM . JVM will handle it.
Yes, your thinking is correct, I think the best way to know answer to "just writing the code", let the code tell you the answer. you can see the following simple example code:
package own;
public class MyExceptionTest {
public void testRuntimeException (){
throw new MyException();
}
public static void main(String[] args) {
try{
new MyExceptionTest().testRuntimeException();
}catch(Exception e){
System.out.println(e.getClass().getName());
}
}
}
class MyException extends RuntimeException{
public MyException(){
super();
}
}
I am a project manager in IT and I have had the same argument over and over with my devs and they simply dont care. Browsing the net, even most people advocate catching and throwing RuntimException... Every time I see it I get unbelievably furious about the inaptitude after 10 years of experience....
Rule No.1:
Never ever throw a runtimeexception in Program if you didnt catch a RuntimeException.
Rule No.2:
Only catch a Runtimeexception in order to some really import stuff that has nothing to do with your software: e.g. send a mail to operations emergency shift, log exception, restart the server....
The reason for this is that in good software there is no stacktrace in a logfile. When feel uncomfortable starting to code do this:
Create new class DevelopmentException Extends Exception.
Then goahead and write your code and catch for exception initially. Then you rethrow it as your very own developmentexception. In the method catching it you log it.
Now: Everyday grep for your very personal DevelopmentException. If you find one this means there is still work to do. Go into your code and see where the Exception came from and catch it beforehand.
Ideally you will never see a DevelopmentException in this part of your program again. Repeat until there are 0 Stacktraces in your Software left and you have perfected Exception handling.
The biggest issue with throwing and catching runtime exception is that the compile ignores it. So this means when one of your colleagues writes a booking interface and throws RuntimeException when there is a value missing (yeah, ppl really do)... ...the compiler will not show you that there might be a runtimeexception. Now, when you dont catch it then your program might just shut down without any logging.
Why is it called RuntimeException?
Many mistake this for Error during Runtime of Program, however it actually means 'An Exception so utterly destructive that the Java Runtime Environment need to be stoppep'. In other words it meand: OutOfMemory, BrokenRam, FaultyImplementation of JRE, etc... basically stuff that tell you: Program cannot run because PC is crashing....
Just my 2 cents.
Anyone experienced the same stuff?
PS: Regarding continous removal of stacktraces:
Once you see an exception try to catch it with e.g. NullpointerException.
When you see Nullpointerexception go to your code and remove the stacktrace, and just log.WARN(NullpointerOccured) and write your Program to retry or so...
Ideally you repeat until you never see a Stacktrace again.
When you cannot see a stacktrace ever it means all that could possibly go wrong is taken care of (Except for RuntimeException of course)
I am designing a program in JAVA that captures results in about 10 iterations. At the end of these iterations all the results must be written into a log file.
If any exception occurs then it should be written on my text file and secondly the program must not stop, it must go on till the last iteration is completed...
That is to say - if some error occur on any part of any iteration the program must not stop here. The error must be mentioned within my results by the name of error and it must go on and update my log file.
My code till now is bit lengthy...used try-catch, the try block is doing my calculations and writing my text file, but I need if incase some exception occurs my program must not stop and that exception must be updated in my log file.
You're looking for the try-catch block. See, for example, this tutorial.
OutputStream os = ....;
PrintStream ps = new PrintStream(os);
while(notDone) {
try {
doStuff();
}
catch(Throwable t) {
t.printStackTrace(ps);
}
ps.print(results);
}
the case is, in this kind of a question, you should better provide us a sample code, then only we can identify the problem without any issue.
If you just need to view the error, then "e.printStackTrace" will help you. The "e" is an instance of class "Exception".
However, if you need to LOG, then "Logger" class will help you, with Exception class.For an example,
try {
f = location.createNewFile();
} catch (IOException ex) {
Logger.getLogger(TestForm.class.getName()).log(Level.SEVERE, null, ex);
}
To do all of these, it is better to surround your code with try catch block
/**
* An exception thrown when an illegal side pit was
* specified (i.e. not in the range 1-6) for a move
*/
public class IllegalSidePitNumException extends RuntimeException
{
/**
* Exception constructor.
* #param sidePitNum the illegal side pit that was selected.
*/
public IllegalSidePitNumException(int sidePitNum)
{
super("No such side pit number: "+sidePitNum);
}
}
How do I use this in a program and then resume for there? I do not want the program to end but want to handle the exception and continue.
You need to use try/catch. You can learn a lot about exception handling from Sun's (Oracle's) exception handling tutorials. In that tutorial look at the sections about Catching and Handling that specific address your question.
For example, in the code that calls the method that may throw this exception:
try {
...call method here...
} catch (IllegalSidePitNumException e) {
// Display message (per your comment to BalusC)
System.err.println(e.getMessage());
e.printStackTrace(System.err);
// You can also handle the exception other ways (but do not ignore it)
// Such as correcting some offending values, setting up for a retry
// logging the information, throwing a different exception
}
...program continues executing here...
Just catch it.
try {
doStuffWhichPossiblyThrowsThisException();
} catch (IllegalSidePitNumException e) {
// Don't rethrow it. I would however log it.
}
continueWithOtherStuff();
Sidenote: If this is an "expected" exception, you might want to inherit it from Exception instead of RuntimeException. RuntimeExceptions are intended to be used when something unexpected happens, for example illegal input due to a programmer error.
Of course, you don't give the context where you intend to use the exception so this is all theory (but you do mention that you want to continue the execution).
As others have said, you can do the following:
try {
doSomething();
} catch (SomeException ex) {
doRecovery();
}
doSomethingElse();
But there is no way to do something like the following in Java:
doSomething();
throw new SomeException(...);
doSomethingElse(); // ... after some handler has "resumed" the exception.
The above is a (hypothetical) example of "resumption model" exception handling, and Java does not support this. (Nor does C#, C++ or any other currently popular programming language ... though a couple of historical languages did support it.) In fact, the Java compiler will give you a compilation error for the above, saying that the statements after the throw are unreachable.