how can null exception enter try-catch branch? - java

My java code throws exception e which is null (debug shows e==null)
How can the code catch this at:
} catch (IOException e) {
e.printStackTrace();
}
If e is null how can it have a type?

Two ideas occur to me:
1) What most debuggers display is e.toString(). If you have an exception object whose toString() is returning null (or "null"), that might explain what you're seeing. What type does the debugger say e is?
2) Another possibility is that your source code doesn't match the class currently executing, and you're at a different line than you think you are. I've been caught out that way.

Related

Fortify throw inside finally bugs

I am getting fortify issue as :
Poor Error Handling: Throw Inside Finally
I am not throwing exception inside finally block, but still it is showing this error.
Please find the code below.`
catch( IOException | JSONException | URISyntaxException e)
{
if(instream == null) {
throw new IOException("InputStream not valid");
}
return e.getMessage();
}finally {
if(instream != null ) {
instream.close();
}
if(urlConnection != null ) {
urlConnection.disconnect();
}
}
No, you are: inStream.close() can throw.
Generally, 'curing' the warning is actually going to make your code worse. This is the problem:
IF the try block throws an uncaught exception
In this case, the finally block is executed. Let's say that the finally block runs in.close();. Especially if the entire reason we got here is that in got disconnected and started throwing IOEx, this is likely to also throw an IOEx. Any exceptions thrown out of a finally block 'overwrite' the exception that caused us to be here, and the stack trace from that close call is far less useful.
So this is bad.
We can fix it by wrapping the in.close() in your finally block in a try { .. } catch (Exception ignore) {}. But then, the other scenario is really bad:
IF we get here 'normally'
It's possible for an input stream to work perfectly, and then when you close it, it throws. For a good long while common wisdom was 'eh, whatever, who cares, I got my data', but that's not a sensible idea: If an input's close ends up throwing, that probably means you didn't actually get all data yet, otherwise, why did it do that? So, now, silently swallowing any exceptions is a bad idea, and we want to throw it.
Without bending over backwards, using a boolean to track how we got to the finally block and depending on it, swallowing that exception or not, it is not possible to do it right.
Because this is so tricky, try-with-resources actually does it right and generates the requisite boilerplate.
Thus, the REAL solution: If you are closing resources in a finally block, don't. Use the try (ResourceType r = new ResourceType()) { ... } syntax instead.
If you truly can't do that, and you also can't make it work by creating a wrapper that is AutoClosable and will for example do nothing if the resource is null, then you're basically forced to tell your linter to stop complaining about this.

Catch exception in Java parameters

How can I catch in exception in Java parameters
Just one example, in code like this
MyClass obj = null;
logger.info("the field is " + obj.field);
a null pointer exception is thrown. Is there a way to automatically do this:
MyClass obj = null;
try {
logger.info("the field is " + obj.field);
} catch(Exception e) {}
Perhaps using Spring AOP, annotations, etc?
Edit: I want something that will catch any exception, so that I never have an exception thrown from a line of code that tries to log.
No there isn't. And you shouldn't do wrap your code in try catch. This may avoid you some runtime exceptions but also could hide real code issues. You could use the Null Object pattern. You create a marker class with empty fields and if a value in your code should be null you assign it to an instance of this marker class. That should work for code under your control, however it doesn't guarantee third party libraries wouldn't throw NPE.
Edit: I want something that will catch any exception, so that I never have an exception thrown from a line of code that tries to log.
That can never be achieved. What you are asking for essentially is a try catch block at the start to end of the main method. Even though you still can get exceptions from other threads for example

Java Exception.getMessage() returns -1

I am trying to debug a piece of production code. I did not write it, so please do not criticize it. I know it is terrible practice for multiple reasons, and I would change it if I could, but I can't.
The code looks like:
try
{
...
// Multiple lines of code that can throw exceptions
...
}
catch (Exception e)
{
System.out.println("Exception: " + e.getMessage());
}
Nowhere in those multiple lines of code is an exception thrown manually.
Despite this, the following is the entirety of what is printed in the case I'm trying to debug:
Exception: -1
The Java documentation for Throwable.getMessage() says
getMessage
public String getMessage()
Returns the detail message string of this throwable.
Returns:
the detail message string of this Throwable instance (which may be null).
All non-native library methods that can throw exceptions are correctly caught around where they are called within the larger try-catch block. So, speaking specifically in regards to Exceptions in the standard JDK, are there any possible Exceptions whose messages are simply "-1"?
The exception name is often a really important part of the exception. Sometimes it's the only thing in the exception. See javadoc of getMessage():
Returns the detail message string of this Throwable instance (which may be null).
Examples of exceptions with no message:
NullPointerException
StackOverflowError
So, println(e.getMessage()) is often meaningless, because it's nothing or entirely without context.
Examples of exceptions where message is meaningless without exception name:
-1 ArrayIndexOutOfBoundsException
foo.txt FileNotFoundException
Always include the exception name too, e.g. using toString():
System.out.println("Exception: " + e.toString());
String concatenation will automatically use toString(), so it can also be just:
System.out.println("Exception: " + e);
Most of the time, it is better to print the stacktrace, so you can see where in the code the exception occurred:
e.printStackTrace(System.out);
use
e.printStackTrace()
you will see where the exception is thrown, and why. My guess is it's going to be an array IndexOutOfBound exception

Catching throwable and handling specific exceptions

Ok I know catching throwable is not a good idea:
try {
// Some code
} catch(Throwable e) { // Not cool!
// handle the exception
}
But recently I was reading through an open sourced code and I saw this interesting (at least to me) piece of code:
try {
// Some Code
} catch (Throwable ex){
response = handleException(ex, resource);
}
private handleException(Throwable t, String resource) {
if (t instanceof SQLEXception) {
// Some code
} else if (t instanceof IllegalArgumentException) {
//some code
} //so on and so forth
}
This doesn't seem to be that bad? What is wrong with this approach?
There are various reasons why you should not catch a Throwable. First of all is, that Throwable includes Errors - and there's normally not much an application can do if one of these appears. Also Throwable reduces your chances of finding out, WHAT has happened. All you get is "something bad has happened" - which might be a catastrophe or just a nuisance.
The other aproach is better but of course I still would not catch Throwable, but try to catch more specific Exceptions, if possible at all. Otherwise you are catching everything and then try to sort out which kind of bad thing happened. Your example could be written as...
try {
...
} catch (SQLEXception ex){
response = ... ;
} catch (IllegalArgumentException ex){
response = ...;
}
...which would reduce the amount of if ( ... instanceof ... ) blocks (which are only needed because the author first decided to catch everything in one big bucket). It something actually throws Throwable, then you don't have much choice, of course.
You are right when you say that catching Throwable is not a good idea. However, the code that you present in your question is not catching Throwable in an evil way but let's talk about that later. For now, the code that you present in your question has several advantages :
1. Readability
If you look at the code carefully, you will notice that even though the catch block is catching a Throwable, the handleException method is checking the type of exception thrown and possibly taking different actions based on the exception type.
The code presented in your question is synonymous to saying:
try {
doSomething();
} catch (SQLEXception ex){
response = handleException(resource);
} catch(IllegalArgumentException ex) {
response = handleException(resource);
} catch(Throwable ex) {
response = handleException(resource);
}
Even if you have to catch 10+ exceptions only, this code can easily take up a lot of lines of code and the multi-catch construct is not going to make the code any cleaner. The code that you present in your question is simply delegating the catch to another method to make the actual method that does the work more readable.
2. Reusability
The code for the handleRequest method could easily be modified and placed in a utility class and accessed throughout your application to handle both Exceptions and Errors. You could even extract the method into two private methods; One that handles Exception and one that handles Error and have the handleException method that takes a Throwable further delegate the calls to these methods.
3. Maintainibility
If you decide that you want to change the way you log an SQLExceptions in your application, you have to make this change in a single place rather than visiting every method in every class that throws an SQLException.
So is catching Throwable a bad idea?
The code that you present in your question is not really the same as catching Throwable alone. The following piece of code is a big no-no:
try {
doSomething();
} catch(Throwable e) {
//log, rethrow or take some action
}
You should catch Throwable or Exception as far away in the catch chain as possible.
Last but not the least, remember that the code you present in your question is framework's code and there are certain errors that the framework can still recover from. See When to catch java.lang.Error for a better explanation.
Catching Throwables out of laziness is a bad idea.
This was particularly tempting before try-multi-catch was introduced.
try {
...
} catch (SomeException e) {
//do something
} catch (OtherException e) {
//do the same thing
} ...
Repeating catch blocks is tedious and verbose, so some people decided to just catch Exception or Throwable and be done with it. This is what should be avoided because:
It makes it difficult to follow what you're trying to do.
You may end up catching a lot of stuff you can't deal with.
You deserve bonus punishment if you completely swallow the Throwable in the catch block. (And we've all seen code that does that...:))
But catching Throwables when it is absolutely necessary is fine.
When is it necessary? Very rarely. In framework-style code there are various scenarios (dynamically loading an external class is the most obvious one), in a standalone application a typical example is to attempt to display/log some kind of error message before exiting. (Bearing in mind that the attempt may fail, so you don't want to put anything critical there.)
As a rule of thumb, if there's nothing you can do about an exception/error, you shouldn't catch it at all.
You posted a link to Jongo, which demonstrates one possible use for this technique: re-using error handling code.
Let's say you've got a large block of error handling code that naturally repeats itself in various places in your code - for example Jongo produces standard responses for some standard classes of errors. It may be a good idea to extract that error handling code into a method, so you can re-use it from all the places it's needed.
However, that's not to say that there's nothing wrong with Jongo's code.
Catching Throwable (rather than using multicatch) is still suspicious, as you're likely to catch Errors that you're not really in a position to handle (are you sure you meant to catch ThreadDeath?). In this situation, if you absolutely have to catch Throwable, it'd be better to "catch and release" (i.e, rethrow anything that you didn't mean to catch). Jongo doesn't do this.
There are exactly two valid uses for using a huge net:
If you will handle everything uniformly, like a top-level catch for logging/reporting, possibly followed by an immediate exit.
To reduce duplication, by exporting all the handling into its own method.
Catch the most derived common ancestor there is to avoid extra-work and increase clarity.
DRY is an important design principle.
In both cases, unless you expected that exception and handled it completely, rethrow.
First of all, catching Throwable makes your application rather intransparent. You should be as explicit as possible on catching exceptions to enable good traceability in exceptional cases.
Let's have a look at the method handleException(...) and see some of the problems that occur by this approach:
you catch Throwable but you only handle Exceptions, what happens if an e.g. OutOfMemoryError of type Error is thrown? - I see bad things to happen...
Regarding good object oriented programming using instanceof breaks the Open-Closed-Principle and makes code changes (e.g. adding new exceptions) really messy.
From my point of view, catch-blocks are exactly made for the functionality that are tried to cover in handleExceptions(...), so use them.
Java 7 solves a bit of the tedium that is multi-catching of similar exceptions with similar handling. You definitely should not be doing what the person has done here. Just catch the appropriate exceptions as needed, it may look ugly but then that's what throws is for, pass it to the method that should catch it and you shouldn't be wasting too much code space.
Check out this link for more information.
Just to provide balance - there is one place where I will always catch (Throwable):
public static void main(String args[]) {
try {
new Test().test();
} catch (Throwable t) {
t.printStackTrace(System.err);
}
}
At least something shows somewhere that something went wrong.
You can always catch different type of exceptions and perform some operations based on the type of the exception you got.
Here is an example
try{
//do something that could throw an exception
}catch (ConnectException e) {
//do something related to connection
} catch (InvalidAttributeValueException e) {
// do anything related to invalid attribute exception
} catch (NullPointerException e) {
// do something if a null if obtained
}
catch (Exception e) {
// any other exception that is not handled can be catch here, handle it here
}
finally{
//perform the final operatin like closing the connections etc.
}

Wrinng a RuntimeException

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

Categories

Resources