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 8 years ago.
Improve this question
I have defined a function:
public MyCar findCar(){
MyCar car = CarManager.findCarById("U983"); //Nullpointer Exception here if no car be found
if(car!=null)
return car;
else
return null;
}
When I invoke the above function in Java, If the above CarManager.findCarById() did not find any car, it returns null, and I try to check in if condition that if it is null return null other wise return the car.
But the findCar() function always stop and raise Nullpointer Exception when findCarById() did not find any car, without go through my if condition. How to get rid of it?
============ findCarById() is a library API I can not modify =================
Throwing or catching NullPointerException is not a really good idea. If you can modify that findCarById, change it.
Otherwise, you can do try-catch here.
MyCar car = null;
try {
car = CarManager.findCarById("U983");
} catch (NullPointerException e) {
car = null;
}
Check (or post) method "findCarById" in your static CarManager class.
You're saying that the findCar() method you posted is throwing a NullPointerException? That's not possible since there are no object dereferences in that method.
Also, that whole if condition is pointless. It's saying "if car is null, return null, else return the car". You might just as well say return car; - it will have exactly the same effect.
How about modifying findCar() like this :
public MyCar findCar(){
MyCar car = null;
try {
car = CarManager.findCarById("U983"); //Nullpointer Exception here if no car be found
}
catch (Exception e){
e.printStackTrace();
}
return car;
}
Related
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 9 months ago.
Improve this question
public int compare(Cat cat1, Cat cat2) {
try {
Cat obj1 = cat1;
Cat obj2 = cat2;
return obj1.getCode().compareTo(obj2.getCode());
//compareTo returns 0/1, getCode returns a string color of cat.
}
catch (ClassCastException e) {
throw new CatRuntimeException("Comparison failed.");
}
}
//want to test the catch part.
If you really want to trigger it
Cat c1 = mock(Cat.class);
Cat c2 = mock(Cat.class);
when(c1.getCode()).thenThrow(new ClassCastException());
yourObject.compare(c1, c2);
You’d want to call the fuction in a way that causes the exception and then check if it gets thrown. Here‘s a link that might help: https://www.baeldung.com/junit-assert-exception
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 3 years ago.
This post was edited and submitted for review 12 months ago and failed to reopen the post:
Original close reason(s) were not resolved
Improve this question
I'm working on nested exceptions in java, I wanted to check the type of my custom exception using the condition (eg. if(t.getCause().getCause() instanceOf MyCustomException)) but this might throw a potential NPE.
So I'm planned to check for null using below condition
if((t.getCause().getCause() != null) && (t.getCause().getCause() instanceOf MyCustomException)) {
..........
}
Is it a good approach, Any suggestions would be appreciated?
Thanks!
Your approach would not work the way you're planning. Let me explain why:
When you use instanceof you are already checking if an object is null (e.g. null is not instanceof myCustomerException, so it is false)
If you are already using instanceof it means your problem is not in t.getCause().getCause(), but might be with t.getCause() or even t.
I would suggest you have a method to do the check for you, so you do a clean call. Something like:
public boolean isTheNestedException(Throwable t) { // Assuming you are using throwable
return t != null && t.getCause() != null && t.getCause().getCause() instanceof MyCustomerException; // Assuming your "MyCustomerException" is a custom exception class
}
You would use it like:
if (isTheNestedException(t) {
....
}
instanceOf does not cause NullPointerException.
JLS 15.20.2. Type Comparison Operator instanceof says:
the result of the instanceof operator is true if the value of the RelationalExpression is not null and the reference could be cast to the ReferenceType without raising a ClassCastException. Otherwise the result is false.
Now, the first getCause() can return null, making the second call cause NPE, so your code should be:
if (t.getCause() != null
&& t.getCause().getCause() instanceOf myCustomeException) {
..........
}
This presumes that t itself cannot be null.
Your proposed code is fragile. If you ever change the nesting, the if will break. A better pattern is to write a general purpose search on causal chains:
#SuppressWarning("unchecked")
public static <T> T getFirstCause(Throwable ex, Class<T> exClass) {
for (Throwable cause = ex; cause != null; cause = cause.getCause()) {
if (exClass.isAssignableFrom(cause)) {
// Unchecked by Java type system, but verified by the if above.
return (T) cause;
}
}
return null;
}
Now you say
if (getFirstCause(t, myCustomeException.class) != null) {
...
}
You can also retrieve the matching instance if needed.
myCustomeException customEx = getFirstCause(t, myCustomeException.class);
if (customEx != null) {
OtherInfo info = customEx.getCustomeExInfo()
}
One if the best ways I've seen is something like
Throwable anException = t.getCause();
while(anException != null){
// Do a thing with with the throwable.
anException = anException.getCause();
}
I didn't test it, but you should get the idea!
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 4 years ago.
Improve this question
I'm thinking about validateEntity. What do you think about it?
T validateEntity(#Nullable T entity)
{
if (entity == null)
{
entity = DEFAULT_ENTITY;
}
return entity;
}
It's not a validation, it's replacement. I think the method name is incorrect.
// replaceIfNull as possible option
T getDefaultIfNull(#Nullable T entity) {
if (entity == null)
return DEFAULT_ENTITY;
return entity;
}
Using thernary operator:
T getDefaultIfNull(#Nullable T entity) {
return entity == null ? DEFAULT_ENTITY : entity;
}
Java 8:
T getDefaultIfNull(#Nullable T entity) {
return Optional.ofNullable(entity).orElse(DEFAULT_ENTITY);
}
With Guava liblary com.google.common.base.Optional<T>:
T getDefaultIfNull(#Nullable T entity) {
return Optional.fromNullable(entity).or(DEFAULT_ENTITY);
}
Guava com.google.common.base.MoreObjects:
T getDefaultIfNull(#Nullable T entity) {
return MoreObjects.firstNonNull(entity, DEFAULT_ENTITY)
}
Actually, as you can see there is the Java 8 tools and external libraries that can establish reasonable doubt on existance of such method.
If you decide yo go without any libraries or using Java version lower than 8, you can stick to the first approach.
It depends on what exactly you want to achieve.
If you want to validate some element, the method should probably return a boolean or a value representing some validation status about the entity, rather than an entity itself.
Otherwise, if you want to replace the element — you cannot actually "replace" an object itself with another object. For instance, the following method returns the given entity if it is not null, or DEFAULT_ENTITY if it is.
T guaranteeNotNull(#Nullable T entity) {
return (entity != null ? entity : DEFAULT_ENTITY);
}
But it depends on the caller if the returned value is actually assigned to a variable, replacing another value. The following snippet has actually no effect:
String someValue = null;
guaranteeNotNull(someValue);
System.out.println(someValue); // Still null
The best thing is actually to either shortcut the method to this:
T guaranteeNotNull(#Nullable T entity) {
return Optional.ofNullable(entity).orElse(DEFAULT_ENTITY);
}
or get rid of the method altogether.
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 5 years ago.
Improve this question
I don't find the appropriate solution for my question. As far as I know returning null is a not a good way to write clean code, as the book Clean Code says. However there are many different opinions about this practice, and I am not sure about which one fits on my function.
private EArea getSimilarExistingArea(EImportArea importedArea) {
for (EArea existingArea : exsitingAreas) {
EList<EPoint> importedAreaPoints = importedArea.getPoly().getPoints();
EList<EPoint> existingAreaPoints = existingArea.getPoly().getPoints();
for (EPoint importedAreaPoint : importedAreaPoints) {
for (EPoint existingAreaPoint : existingAreaPoints) {
if (importedAreaPoint.equals(existingAreaPoint))
return existingArea;
}
}
}
return null;
}
What should I return if there is not an existing similar area?
PD: For optimize my code I am breaking the loops with the return if an existing area is founded.
You should take a look at the Optional class!
Make your method return type Optional<EArea> and simply return Optional.ofNullable(existingArea) you will have to slightly modify your Code but the benefits of Optional are really worth it!
Finally I used Optional Class to solve my problem.
Here is the code:
private Optional<EArea> getSimilarExistingArea(EImportArea importedArea) {
for (EArea existingArea : baseLineService.getBaseLine().getAreas()) {
EList<EPoint> importedAreaPoints = importedArea.getPoly().getPoints();
EList<EPoint> existingAreaPoints = existingArea.getPoly().getPoints();
for (EPoint importedAreaPoint : importedAreaPoints) {
for (EPoint existingAreaPoint : existingAreaPoints) {
if (importedAreaPoint.equals(existingAreaPoint))
return Optional.of(existingArea);
}
}
}
return Optional.empty();
}
And here is how I check the returned value:
if (getSimilarExistingArea(importedArea).isPresent())
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 7 years ago.
Improve this question
I'd like to make this into a boolean that will return true or false.
I simply got no idea how to , so I need some help.
public static void checkUSPASS(String a,String b) {
try {
con = DriverManager.getConnection(url,username, password);
stmt = con.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE,ResultSet.CONCUR_READ_ONLY);
String sql;
sql = "SELECT * FROM db Where Email='"+a+"' and Password='"+b+"'";
ResultSet rs = stmt.executeQuery(sql);
if(rs.next())
{
//return true
}
else
{
//return false
}
}
catch (SQLException ex) {
ex.printStackTrace(); }
}
I should probably get all declarations out , but I'd like to hear what do you think guys.
While this is not the answer to your question, but I believe it will help you to make your method better. Probably comment will be more suitable, but comments with large piece of text are hard to read.
Don't use SQL query string composition like you do. Use PreparedStatement instead of that.
Process exceptions inside of your method or throw them further. Printing stack trace is not the exception processing, it hides the problem from the end-user.
To throw the exception further add throws SQLException to your method declaration, and remove try/catch construction from the method body. It will allow the caller to process the exception and will avoid many hard-to-catch bugs later.
Don't store passwords as Strings, it is a bad practice. Hash passwords with salt and store password hashcode.
And finally your method declaration should look like that:
public static boolean checkUSPASS(String username,String hashCode) throws SQLException
First change the method signature to return a value:
public static boolean checkUSPASS(String a,String b)
Then return a value from within the method:
return true;
or:
return false;
Note that all code paths must return some value. So you have this in your try block:
if (rs.next()) {
return true;
}
else {
return false;
}
But in the event of reaching your catch block, something must still be returned:
catch (SQLException ex) {
ex.printStackTrace();
return false;
}
To change a function to boolean in java all you have to do is change void to boolean in your function definition and return true or false at all end points.