NullPointerException not being caught - java

I am using Java reflection as such:
try {
method.invoke(someObject);
} catch (IllegalAccessException | IllegalArgumentException | InvocationTargetException | NullPointerException e) {
//Do something
}
method is retrieved from iterating through getMethods() from "Set<Method> getMethods = new HashSet<Method>(Arrays.asList(curObject.getClass().getMethods()))"
someObject is not null, but within the method call it makes a call to something that results in a NullPointerException.
However, the code still errors out with a NullPointerException with the stack trace pointing back to "method.invoke(someObject);".
Why doesn't the catch work? Has it something to do with reflection?

i think you should try this:
try
{
// your code may error occures !!
}
catch(NullPointerException e)
{
//do your work here
}
catch(InvocationTargetException e)
{
//do your work here
}
catch(IllegalAccessException e)
{
//do your work here
}
catch(IllegalArgumentException e)
{
//do your work here
}
catch(Exception e)
{
//do your work here
}
here all your Exceptions catch in multiple catch blocks.

If I read the stack trace correctly, it is not a NullPointerException being thrown, but a com.mapp.node.logging.exception.ConstructingFatalThrowableException with the message (and probably the cause) "java.lang.NullPointerException".
The first line of a NullPointerExcpetion stack trace would actually start with java.lang.NullPointerException.
To check this, you could just add ConstructingFatalThrowableException to your catch block.

That's not a NPE: it's a com.mapp.node.logging.exception.ConstructingFatalThrowableException thrown by some funky code instrumented to intervene when building NPEs.
Read the stack from bottom-up:
com.mapp.node.logging.exception.ConstructingFatalThrowableException: java.lang.NullPointerException
at com.mapp.server.util.ExceptionInstrumentationUtil.handleFatalThrowable(ExceptionInstrumentationUtil.java:212)
at com.mapp.server.util.ExceptionInstrumentationUtil.access$000(ExceptionInstrumentationUtil.java:32)
at com.mapp.server.util.ExceptionInstrumentationUtil$2.sample(ExceptionInstrumentationUtil.java:164)
at com.mapp.server.util.ExceptionInstrumentationUtil$2.sample(ExceptionInstrumentationUtil.java:160)
at com.google.monitoring.runtime.instrumentation.ConstructorInstrumenter.invokeSamplers(ConstructorInstrumenter.java:207)
at java.lang.RuntimeException.<init>(RuntimeException.java:52)
at java.lang.NullPointerException.<init>(NullPointerException.java:60)
The thread is at NullPointerException.java:60 where there is a call to java.lang.RuntimeException.<init> (ie. the superclass constructor) where (at RuntimeException.java:52) there's what the JVM is instrumented to think of as a call to com.google.monitoring.runtime.instrumentation.ConstructorInstrumenter.invokeSamplers (I believe it takes the place of a super()?).
Anyhow - your exception is thrown in ExceptionInstrumentationUtil.java:212.

The reason you are not catching the exception is that it's not a NullPointerException, but a com.mapp.node.logging.exception.ConstructingFatalThrowableException. This exception is being thrown with the message (which follows the exception's name) "java.lang.NullPointerException" and that's the source of confusion. Try to catch the ConstructingFatalThrowableException instead of the NPE and see if it works.
Also, note that you shouldn't be catching a NullPointerException. It is a RuntimeException and this group of exceptions usually indicates a programming error, in which case you shouldn't "handle" it, because if you knew to expect it, you should have avoided the error. See what the docs say:
Runtime exceptions represent problems that are the result of a
programming problem, and as such, the API client code cannot
reasonably be expected to recover from them or to handle them in any
way. Such problems include arithmetic exceptions, such as dividing by
zero; pointer exceptions, such as trying to access an object through a
null reference (...)
With this in mind, just avoid the NullPointerException. Check an example below:
if(var!= null) {
//Normal code here
}
else {
//Handle the null pointer here
}

Related

why is the Catch exception e printing instead of doing what is in Try

I am confused why it is going to catch and print the error occurred message when I run my code since it runs and just prints the message I can't tell what the error could be
Note: this is my very first time using try and catch my professor told us to use it but haven't really learned how it works fully yet so I'm not sure if the problem is with that or if it's just with my code
public static void main (String [] args) {
try {
File file = new File("in.txt");
Scanner scanFile = new Scanner(file);
...
} catch(Exception e) {
System.out.println("Error");
}
}
Do not catch an exception unless you know what to do. It is common that you don't - most exceptions aren't 'recoverable'.
So, what do you do instead?
Simplest plan: Just tack throws Exception on your main method. public static void main(String[] args) methods should by default be declared to throws Exception, you need a pretty good reason if you want to deviate from this.
Outside of the main method, think about your method. Is the fact that it throws an exception an implementation detail (a detail that someone just reading about what the method is for would be a bit surprised by, or which could change tomorrow if you decide to rewrite the code to do the same thing but in a different way)? In that case, do not add that exception to the throws clause of your method. But if it is, just add it. Example: Any method whose very name suggests that file I/O is involved (e.g. a method called readFile), should definitely be declared to throws IOException. It'd be weird for that method not to throws that.
Occasionally you can't do that, for example because you're overriding or implementing a method from an interface or superclass that doesn't let you do this. Or, it's an implementation detail (as per 2). The usual solution then is to just catch it and rethrow it, wrapped into something else. Simplest:
} catch (IOException e) {
throw new RuntimeException("uncaught", e);
}
Note that the above is just the best default, but it's still pretty ugly. RuntimeException says very little and is not really catchable (it's too broad), but if you don't really understand what the exception means and don't want to worry about it, the above is the correct fire-and-forget. If you're using an IDE, it probably defaults to e.printStackTrace() which is really bad, fix that template immediately (print half the details, toss the rest in the garbage, then just keep on going? That's.. nuts).
Of course, if you know exactly why that exception is thrown and you know what to do about it, then.. just do that. Example of this last thing:
public int askForInt(String prompt) {
while (true) {
System.out.println(prompt + ": ");
try {
return scanner.nextInt();
} catch (InputMismatchException e) {
System.out.println("-- Please enter an integral number");
}
}
}
The above code will catch the problem of the user not entering an integer and knows what to do: Re-start the loop and ask them again, until they do it right.
Just add throws Exception to your main method declaration, and toss the try/catch stuff out.
There are a couple of problems with your current code:
catch (Exception e) {
System.out.println("Error occured...");
}
Firstly, you are not printing any information about the exception that you caught. The following would be better:
catch (Exception e) {
System.out.println(e.getMessage()); // prints just the message
}
catch (Exception e) {
System.out.println(e); // prints the exception class and message
}
catch (Exception e) {
e.getStackTrace(System.out); // prints the exception stacktrace
}
Secondly, for a production quality you probably should be logging the exceptions rather than just writing diagnostics to standard output.
Finally, it is usually a bad idea to catch Exception. It is usually better to catch the exceptions that you are expecting, and allow all others to propagate.
You could also declare the main method as throws Exception and don't bother to catch it. By default, JVM will automatically produce a stacktrace for any uncaught exceptions in main. However, that is a lazy solution. And it has the disadvantage that the compiler won't tell you about checked exceptions that you haven't handled. (That is a bad thing, depending on your POV.)
now null printed out.
This is why the 2nd and 3rd alternatives are better. There are some exceptions that are created with null messages. (My guess is that it is a NullPointerException. You will need a stacktrace to work out what caused that.)
Catching Exception e is often overly broad. Java has many built-in exceptions, and a generic Exception will catch all of them. Alternatively, consider using multiple catch blocks to dictate how your program should handle the individual exceptions you expect to encounter.
catch (ArithmeticException e) {
// How your program should handle an ArithmeticException
} catch (NullPointerException e) {
// How your program should handle a NullPointerException
}

How to let if statement complete even if there is a NullPointerError

I have this if statement:
if (!this.updateTime.equals(ProductionBlocking
.get(this.keyReader.getUpdateTime(this.config.configUuid.toString(),
KeyType.PLUSSTAR)))) {
...
}
Sometimes the below is null so I get a NullPointerError.
ProductionBlocking
.get(this.keyReader.getUpdateTime(this.config.configUuid.toString(),
KeyType.PLUSSTAR))`
Is there any way I can let the program run on even if there is a null pointer? Basically in this case I'd like the if to determine they arent equal.
You can catch the NullPointerException and then do nothing with it... although this is generally not recommended. You should try to handle this exception in the catch block and try to figure out why you are getting a npe and fix that.
try {
// your code that throws the npe
} catch (NullPointerException e) {
// catch it and do nothing (or handle it!)
}
// ... the rest of your code

How to handle exceptions that you didn't expect even thought it is declared on the documentation?

When there are methods that throw exceptions and you know these exceptions will not be thrown, what should you do?
Many times I see people just logging the exception, but I wonder if there is a build in exception in java that means something like: "This exception should not have been thrown".
For example, imagine I have a code that calls StaticClass.method(someObject) and this method throws a SpecificException when someObject is not valid. What should you do in the catch block?
try {
StaticClass.method(someobject);
} catch (SpecificException e) {
// what should I do here?
}
If when calling the method you know for sure that it will not throw an exception because of previous checks you should throw a RuntimeException wrapping the SpecificException.
try {
StaticClass.method(someobject);
} catch (SpecificException e) {
//This is unexpected and should never happen.
throw new RuntimeException("Error occured", e);
}
Some methods already throw a RuntimeException when they fail to perform their purpose.
//Here we know for sure that parseInt(..) will not throw an exception so it
//is safe to not catch the RuntimeException.
String s = "1";
int i = Integer.parseInt(s);
//Here instead parseInt(..) will throw a IllegalArgumentException which is a
//RuntimeException because h is not a number. This is something that should
//be fixed in code.
s = "h";
i = Integer.parseInt(s);
RuntimeExceptions don't require a try/catch block and the compiler will not be mad at you for not catch them. Usually they are thrown where something in your app code is wrong and should be fixed. Anyway there are cases where catching a RuntimeException is useful.

Try Catch block works but test assertThrows fail (Junit 5)

I am trying to follow this tutorial JUnit 5: How to assert an exception is thrown?
I use Java 10, IntelliJ 2018 and Junit 5.
I make a calculator app that adds 2 fractions. It checks whether the input has 0 in the denominator.
When I run the test The exception Message get printed out "Undefined Math Expression" but my IDE says "Expected java.lang.Throwable to be thrown, but nothing was thrown." I think there is some problem with the scope of my code? I'm a newbie, please be kind. I provided the code and the test below:
public class Calculator {
public static int[] calculate (int firstNumerator, int firstDenominator, int secondNumerator, int secondDenominator) {
String exceptionMessage = "Undefined Math Expression";
int resultNumerator;
int resultDenominator;
int[] result = new int[2];
resultNumerator = (firstNumerator * secondDenominator) +
(secondNumerator * firstDenominator);
resultDenominator = firstDenominator * secondDenominator;
try {
if (resultDenominator == 0) {
throw (new Throwable(exceptionMessage));
} else {
result[0] = resultNumerator;
result[1] = resultDenominator;
}
} catch (Throwable e) {
System.out.println(e.getMessage());
}
return result;
}
}
The test:
class CalculatorTest {
#Test
void denominatorContainsZero() {
assertThrows(Throwable.class, () -> {
Calculator.calculate(0,0,0,0);
});
}
}
The misunderstanding here appears to be in what JUnit can actually see.
JUnit isn't magical: it's just plain old Java. It can't see inside your methods to see what they are doing. All it can see is what any other code can see when it executes a method: the return value and uncaught exceptions (as well as any side effects of the method, if they are visible to the calling code).
Your method here doesn't throw an exception from the perspective of a caller: internally, it throws the exception, but it catches and handles it.
If you want JUnit to test that an exception is thrown, you need to not catch that exception.
It is never (*) the right thing to do to throw an exception and then catch and handle it yourself. What's the point? You can simply do the thing you do to handle it, without throwing the exception. Exceptions are expensive to throw, because of the need to capture the entire stack trace.
Throwable is never (*) the right exception to throw. It's the exception "equivalent" of returning Object: it conveys no type information about the exception to the caller, who then either has to do a lot of work to try to handle it; or, more realistically, should just propagate it themselves. IllegalArgumentException is the right exception to throw here, if you actually needed to throw (and not catch) an exception.
Throwable is rarely the right thing to catch. Throwable is a supertype of both Exception and Error, so you might unintentionally catch an Error, like OutOfMemoryError, which shouldn't be caught because there is nothing reasonable to do except crash your program. Catch the most specific type you can; which also means that you should throw the most specific type you can (or, at least, a type appropriate to the abstraction).
(*) This is "never" as in "ok, there are a limited number of circumstances where it may be appropriate". But unless you understand what these are, don't.
The Throwable is catched by try catch block, so Junit can not access it. Try remove the try catch block.
You are not actually throwing exception, you are catching it. For this to work, you should remove try catch block.

How do i handle the exception in an own function that Java compiles again?

As mentionend in the Subject: Java forces me to return something, because the handling of the Exception is in an own function.
public String returnLel(String mattDamon) {
try {
trick(mattDamon); // The LelException could be thrown
return "lel";
} catch (LelException e) {
handleException();
}
}
public void handleException() {
throw new RuntimeException();
}
`
Your code will not compile because the compiler is not "clever" enough to know you are throwing a RuntimeException in handleException.
In order for your code to compile you can either:
directly throw new RuntimeException(); in your catch statement (ugly)
return null after invoking handleException(); (acceptable, but still kind of ugly)
add a finally statement to finalize your method and return null or whatever if some condition has not been met (recommended)
Also note that I'm assuming LelException extends RuntimeException, otherwise your catch statement won't compile.
Well it is up to you on how you will handle the situation.
If you are able to handle the exception by say logging it and just return null as most of the comments imply that is totally o.k.
Just consider that this situation could also mean that the method "returnLel" might not be the correct place to handle this exception but to let the caller decide what to do in this situation by "throwing it further" like so:
public String returnLel(String mattDamon) throws LelException{
trick(mattDamon); // The LelException could be thrown
return "lel";
}
This means if the caller calls your returnLel-Method he will have to try/catch the Exception (or throw it further up) and could in this case mean a better design because the caller will not receive null or a String' but aStringor aLeLException` instead
Move the return statement out of the try catch.
The try block should surround the part where an exception could be thrown, what the return statement not does.
Here the java tutorials for some basic knowledge about this topic:
The try Block
The catch Block
The finally Block

Categories