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 1 year ago.
Improve this question
I am new to Java so please don't mind the syntax errors. I want to check if string1 OR string2 is null. If one of them is null then I want to throw a NullPointerException. Also, the return type of my method should be String.
public String handleException(Activity a) {
try {
if(a.string1.equals(null) || a.string2.equals(null))
throw new NullPointerException();
}
catch(NullPointerException e) {
return "Null value found";
}
}
I think you are trying to do that:
public String handleException(Activity a) {
if(a.string1 == null || a.string2 == null) {
// if string1 or string2 is null, throw your exception
throw new NullPointerException("Null value found");
}
// do something now that you know your strings aren't null
return "something";
}
To check if a string is null, you can just use ==
One suggestion is to separate the error handling from the business logic:
public String handleException(Activity activity) {
try {
handleActivity(activity);
}
catch(NullPointerException e) {
return "Null value found";
}
}
private void handleActivity(Activity activity) {
// or some other logic that might cause a NullPointerException
System.out.println(activity.string1.length());
System.out.println(activity.string2.length());
}
But normally NPE's are not caught explicitly, we try to write code that doesn't cause them. There are several ways to check, like using JSR 380:
public class User {
#NotNull(message = "Name cannot be null")
private String name;
You can also check yourself:
if (activity.string1 == null) {
...
In this case you should use == because null is not an Object (and cannot be autoboxed as an Object) and therefore cannot be evaluated by the equals(Object) method. Null is a special value (AKA the billion dollar mistake) which indicates that a variable which is declared as an Object actually refers to nothing.
Technically speaking you don't even need a try-catch block for this operation
You could simply do
public String handleException(Activity a) {
if(a.string1 == null || a.string2 == null){
return "Null value found";
}
// return normal case value
}
But from what I understood you just want to see how try-catch blocks work, so maybe you could explain more what you need exactly.
Related
Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
This question does not appear to be about programming within the scope defined in the help center.
Closed 5 years ago.
Improve this question
Below is the code I have written to build a key using two strings. If either of them is null, empty or blank use the other string to build the key. However if both of them does not qualify, return an empty string. I would like to write a better and efficient piece of code. Here is my sample code
if (!StringAssistant.isBlank(string1) && !StringAssistant.isBlank(string2)) {
return StringAssistant.append(string1, string2);
}
if (StringAssistant.isBlank(string1) && !StringAssistant.isBlank(string2)) {
return string2;
}
if (!StringAssistant.isBlank(string1) && StringAssistant.isBlank(string2)) {
return string1;
}
return "";
You may do something as "simple" as :
return StringAssistant.append(StringAssistant.isBlank(string1)?"":string1,StringAssistant.isBlank(string2)?"":string2);
Simply append the two string and return the value
return string1+string2;
or if you want to use your StringAssistant.append
return return StringAssistant.append(string1, string2);
Notice that the empty string doesn't has an impact on the return value. So if you append the string and return it will result the same.
If the string can be null then you need to handle the null value separately. if either string is null then you can return an empty string. You can handle it in your append method.
You can refactor the code as shown below, I suggest you evaluate the isBlank for the both the strings first (so that for large strings you would get the results quicker):
boolean string1Blank = !StringAssistant.isBlank(string1);
boolean string2Blank = !StringAssistant.isBlank(string2);
if(string1Blank && string2Blank) {
return StringAssistant.append(string1, string2);
} else if(string1Blank) {
return string2;
} else if(string2Blank) {
return string1;
} else {
return "";
}
This question already has answers here:
Java Compiler Error: Missing Return Statement
(2 answers)
Closed 4 years ago.
I'm using the code below in a Triangle class to allow the user to set the first, second, or third point of a declared Triangle.
public Point get(String p) throws IllegalArgumentException {
IllegalArgumentException e = new IllegalArgumentException();
try {
if (p == "first") { return first; }
else if (p == "second") { return second; }
else if (p == "third") { return third; }
else { throw e; }
}
catch (e) {
System.out.println("Error: " + e);
}
}
The compiler is telling me:
Triangle.java:41: error: missing return statement
}
^
But I thought the point of the catch statement was to be able to catch an error and return a string describing the error, without having to worry about matching the function's return type.
Because you're missing a return statement.
The method declares that it returns something, so it must return something (or throw an exception). The compiler can't guarantee that any of the return statements in the try block will be reached if an exception is thrown before any of them execute. So the catch block also needs to return something (or throw an exception, or return something after the try/catch construct entirely).
Edit: Looking again, you're also potentially missing a return in the try block. (If you don't have one after the entire try/catch structure.) What if none of the conditions in the if/else structure are satisfied? Nothing is returned. Which is invalid.
Basically, all logical paths must result in a valid exit of the method. You've missed two such paths.
You're not returning anything in your function on several paths.
But I thought the point of the catch statement was to be able to catch an error and return a string describing the error, without having to worry about matching the function's return type.
That's not at all what a try-catch does, and moreover your function is declared to return a Point not a String.
try-catch simply "catches" a Throwable (Error or Exception) and allows you to run some code when it is thrown instead of simply terminating the application with an Uncaught Exception/Error.
You need to return some value from your function after the try-catch there is no way to return a string, nor is there a language construct in place that behaves like you've explained your understanding of try-catch.
Also your code cna't actually throw an IllegalArgumentException so your catch block will never get called. In this case, it sounds like what you want is instead something like this
public Point get(String p) throws IllegalArgumentException {
if (p == null) { throw new IllegalArgumentException(); }
if (p.equals("first")) { return first; }
else if (p.equals("second")) { return second; }
else if (p.equals("third")) { return third; }
else { throw new IllegalArgumentException(); }
}
The code could then be called like so
Point p;
try {
p = get("notFirst");
} catch (IllegalArgumentException ex) {
//oh no, we gave a bad argument, and the method told us nicely.
}
You are missing two parts:
1. A return statement in try block for else condition
2. Catch block doesn't lead to a return statement or a throw statement
I don't know if type of first, second, third variables are string or Point, but you should return with Point, because your function is :
public Point get(String p) {
...
}
You have three if statements. What happens when the input doesn't satisfy any of those? Your method doesn't have a return statement for that case.
It says it must return a string. But it already is. Then it says that it must have a return statement. But there is one there.
public String description() {
String description = "";
if (description != null)
return description;
}
because if description is null then that return statement is never executed.
your code must be modfied to some thing like this
public String description() {
String description = "";
if (description != null){
return description;
}else{
return null;
}
}
I know that description is not equal to null but the compiler complains because if that if block is never executed then the method will not have a return statement, hence you need to have one outside it too.
To answer your question the reason you get the error the you must have a return statement is that having the return statement within a conditional branch means that there is a possibility that it will not execute. Since this method requires a return type you must include an else condition to return a value so all branches are covered.
Since Java performs a "pseudo compilation" it doesn't know that "description" is clearly not null until it runtime.
I just saw that you are wanting the method to do nothing in the event "description" is null. In this case I would recommend throwing an exception:
#SuppressWarnings("unused")
public String description() throws ValidationException {
String description = "";
if (description == null){
throw new ValidationException("Some Error Message");
}
return description;
}
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 8 years ago.
Improve this question
I have a method with the following if-else-if chain:
if(downstreamActual.getNumber() <= downstreamRecommended.getNumber()){
downstreamActual.setInvalid();
showErrorWindow();
throw new NumberFormatException();
}else if(upstreamActual.getNumber() <= upstreamRecommended.getNumber()){
upstreamActual.setInvalid();
showErrorWindow();
throw new NumberFormatException();
}else if(biUpstreamActual.getNumber() <= biUpstreamRecommended.getNumber()){
biUpstreamActual.setInvalid();
showErrorWindow();
throw new NumberFormatException();
}else if(biDownstreamActual.getNumber() <= biDownstreamRecommended.getNumber()){
biDownstreamActual.setInvalid();
showErrorWindow();
throw new NumberFormatException();
}
Every step we do the same work (call the same method for first object that uses in boolean expression, call showErrorWindow() and throw an Exception)
What are some good techniques especially using Java 8 to make this code more manageable?
Based on your comment, I don't think you need Java 8 constructs.
Just use a method :
public void validate (NumberTextBox actual, NumberTextBox recommended)
{
if(actual.getNumber() <= recommended.getNumber()) {
actual.setInvalid();
showErrorWindow();
throw new NumberFormatException();
}
}
Then call it 4 times :
validate (downstreamActual,downstreamRecommended);
validate (upstreamActual,upstreamRecommended);
...
Since the first one that fails would throw an exception, thus preventing the rest of them from being tested, you don't need the if else-if structure.
I cannot see the java 8 involvement here, but one thing you could do is create a method for that piece of if-else chain in the following manner:
public void handleStreams() throws NumberFormatException {
if(downstreamActual.getNumber() <= downstreamRecommended.getNumber()) {
setInvalid(downstreamActual);
} else if(upstreamActual.getNumber() <= upstreamRecommended.getNumber()) {
setInvalid(upstreamActual);
} else if(biUpstreamActual.getNumber() <= biUpstreamRecommended.getNumber()) {
setInvalid(biUpstreamActual);
} else if(biDownstreamActual.getNumber() <= biDownstreamRecommended.getNumber()) {
setInvalid(biDownstreamActual);
} else {
return;
}
showErrorWindow();
throw new NumberFormatException();
}
public void setInvalid(MyObject stream) {
stream.setInvalid();
}
If those streams have a common super class then you can implement this directly in them. In other words if
public class DownstreamActual extends CustomStream {
then you can add recommendation as a variable to the CustomStream class
public int recommendedValue;
and set it when you create the instance.. Then you can create a method which will check the values
public void checkRecommendedValue() {
if(this.getNumber() <= this.recommendedValue){
this.setInvalid();
showErrorWindow();
throw new NumberFormatException();
}
}
One thing you can do with java 8 is avoid making a separate method (if that calls to you) and create one right inside your method using the new syntax:
BiConsumer<Thing, Thing> check = (actual, recommended) -> {
if (actual.getNumber() <= recommended.getNumber()) {
actual.setInvalid();
showErrorWindow();
throw new NumberFormatException();
}
};
check.accept(downstreamActual, downstreamRecommended);
check.accept(upstreamActual, upstreamRecommended);
check.accept(biUpstreamActual, biUpstreamRecommended);
check.accept(biDownstreamActual, biDownstreamRecommended);
This question already has answers here:
Hibernate Parameter value [568903] did not match expected type [java.lang.Long]
(3 answers)
Closed 9 years ago.
I have the following code
private Long projectNumber; // with getters and setters
and when I am checking whether projectNumber is null or not, I am getting null pointer exception at the if condition
if(selected.getProjectNumber()!=null){
// do something
}
What could be the reason for this even though Long is a wrapper class.
If I change projectNumber from Long to String, it works fine.
Update 1
private Project selected = new Project();
public Project getSelected() {
return selected;
}
public void setSelected(Project selected) {
this.selected = selected;
}
I am getting selected value in ManagedBean of JSF in the following method
public void onRowSelect(SelectEvent event) {
}
projectNo getters and setters
public Long getProjectNo() {
return projectNo;
}
public void setProjectNo(Long projectNo) {
this.projectNo = projectNo;
}
The problem you have is because selected is null, projectNumber. Change the check to something like:
if(selected != null && selected.getProjectNumber()!=null){
// do something
}
Or alternatively add a separate check for selected above.
If you get an NPE here:
if(selected.getProjectNumber()!=null){
and all getProjectNumber() does is return projectNumber, this strongly indicates that selected is null.
the problem is that selected is null. Check it like:
if(selected != null && selected.getProjectNumber()!=null){
// do something
} else {
// here: selected = null OR projectNumber of selected is null
}
did you check if selected is null
you can do the following
if(null != selected)
{
if(null != selected.getProjectNumber())
{
// do something
}
}
Your object selected is apparently null, try to do:
if ((selected != null) && (selected.getProjectNumber()!=null)){
// do something
}
From what you posted, it sems that the problem is that the object referred by the selected variable is null. You have to check that too:
if(selected !=null && selected.getProjectNumber()!=null){
// do something
}
Explanation: Doing it this way, as the boolean AND (and the OR) operator evaluates only the left condition if it is false, not touching the right side, you won't get a NullPointerExceptyion anymore.
EDIT As OP mentioned that by changing the variable to String the problem is not encountered, as 0xCAFEBABE's suggestion implies, the same error might be possible if the getter returns (or somehow internally uses) a simple long value instead of a Long object, and the value of the variable is null:
/** error getter */
public long getProjectNumber() {
//this would trz to convert null, but what will it convert to? A NullPointerExecption...
return projectNumber;
}