Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 7 days ago.
Improve this question
#Override
public CartPojo save(CartPojo cartPojo) throws IOException {
Cart cart;
if (cartPojo.getProductid() != null) {
cart = cartRepo.findById(cartPojo.getProductid().orElseThrow(() -> new RuntimeException("Not Found")));
} else {
cart = new Cart();
}
An error occur in orElseThrow and I can't fix it.
You are checking getProductid() for nullity, however since it (looks like it) returns an Optional, you should instead be checking if it is empty.
if (cartPojo.getProductid().isPresent())
as an added bonus, you can use the Optional type a little bit more elegantly:
#Override
public CartPojo save(CartPojo cartPojo) throws IOException {
Cart cart = cartPojo.getProductid()
.map(cartRepo::findById)
.orElseGet(Cart::new);
// ...
}
This accomplishes the same thing as your above code, but takes advantage of some of the niceties of the Optional type. It gets rid of needing to throw a RuntimeException in a scenario that should never happen.
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 7 months ago.
Improve this question
I'm trying to create a function that can recognize the parent-child loop.
Imagin
Object A is a parent of Object B
Object B is a parent of Object C
create a function that can prevent the parent-child loop. the function should give at least two parameters (childName, parentName) and get errors if the relationship creates a loop. in the above example if we pass (A, C) should print or pass string:
"A is the parent of C"
I know how to create this function(you can provide answer with any language):
private static void restrict_ParentChild_Loop(Object A, Object B) throws Exception {
if (A.parent == null)
return;
if (A.parent.equals(B)) {
throw new Exception("");
} else {
restrict_ParentChild_Loop(A.parent, B);
}
}
My main question is about how to provide the right message in the Exception. ("A is the parent of C")
My main question is about how to provide right message in the Exception.
I'm still wondering why that's not the question title itself.
Since this question is likely opinion-based... I'll give my shot?
Your code at:
throw new Exception("");
Will throw an Exception like this:
java.lang.Exception: At ...
So it will be even better if you just tell it what you want it to show in the first place:
throw new Exception(A.parent+" is the parent of "+B.child);
//This throws:
java.lang.Exception: A is the parent of C: At ...
Which results in:
private static void restrict_ParentChild_Loop(Object A, Object B) throws Exception {
if (A.parent == null)
return;
if (A.parent.equals(B)) {
throw new Exception(A.parent+" is the parent of "+B.child);
} else {
restrict_ParentChild_Loop(A.parent, B);
}
}
Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 11 months ago.
Improve this question
I wanted to add an array as an instance field, also a part of an object, however it gives me interesting errors when i try to do so:
class Surgeon {
private String[] surgeons;
public Surgeon() {
this.surgeons = {"Romero", "Jackson", "Hannah", "Camilla"};
}
public static void main(String[] args) {
Surgeon surg = new Surgeon();
}
}
And it gives me three errors.
This does not make any sense bc is it not how you initialize an array?
You have to add the operator "new" to instantiate the array in the class constructor
public Surgeon() {
this.surgeons = new String[]{"Romero", "Jackson", "Hannah", "Camilla"};
}
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 4 years ago.
Improve this question
I want to know if it's a good practice encapsulate a throw in a method and call it in a return method
int returnMethod(){
if(ok){
return 1;
}
alwaysReturnRuntimeException();
return 1; //Fake
}
void alwaysReturnRuntimeException(){
if(specificError){
throw new OneRuntimeException();
}
// General error
throw new GeneralRuntimeException();
}
Or it's better generate the exception, but don't throw. Only return it and throw it on parent method.
int returnMethod(){
if(ok){
return 1;
}
throw buildException();
}
void buildException(){
if(specificError){
return new OneRuntimeException();
}
// General error
return GeneralRuntimeException();
}
I would say a method that decides which kind of exception has to be thrown is a valid approach to reuse code, but only if it really fits your application design (without knowing more details about the rest of the code, I can't give a well-founded alternative). However, I strongly advise against unchecked exceptions in your code (but that's another story, and kind of subjective).
Two recommendations in case you really need this approach:
Name unambiguously your throwing method showing its direct intention, something like throwMyException() (alwaysReturnRuntimeException() is a bad name for a method that returns nothing)
Even though it is not required by the compiler in the case of unchecked exceptions, declare the throwable exceptions in the method signature, in order to avoid obfuscation.
Your code might be like this:
int returnMethod(){
if(!ok){
throwRuntimeException();
}
return 1;
}
void throwRuntimeException() throws OneRuntimeException, GeneralRuntimeException {
if(specificError){
throw new OneRuntimeException();
}
// General error
throw new GeneralRuntimeException();
}
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 5 years ago.
Improve this question
I am currently making an application that uses an api and it prints out information about that thing. So basically it gets the api and If i do System.out.println(result.getPlayer().get("displayname")); it will return the display name of the player that I am searching for. I was wondering if there was a way to make result.getPlayer().get("displayname") a variable because I have hundreds of statistics that I need to gather. so is it possible to have that line of code called displayname? Sorry if you don't understand.
I suggest that you make a special statistics/logging class that has static methods specifically for this. For example with your case, the following class can be used both to get the name and to print it. Of course you can combine them into a single method if you want just one functionality.
public class StatsLog {
public static String getPlayerDisplayName(final Result result) {
return (result == null)
? null
: result.getPlayer().get("displayname");
}
public static void printPlayerDisplayName(final Result result) {
final String displayName = getPlayerDisplayName(result);
if (displayName != null) {
System.out.println(displayName);
}
}
}
And when you call it:
StatsLog.printPlayerDisplayName(result);
You can use a getter like #Andrew Tobilko said. like this:
public String getDisplayName(){
return (result != null)? result.getPlayer().get("displayname") : "";
}
However, it depends on what is the "result" and the design of your class. And make sure to check for Null.
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 6 years ago.
Improve this question
To be more specific, I want to write a code that throws IllegalArgumentException if the given value is negative. Should I include this code inside of setter/constructor or should I check the value when the appropriate method is called? (Eg: start(), init(), print() or run(). whatever.)
My code (simplified):
public class LLUAlgorithm {
private int temperature;
public int getTemperature() {
return temperature;
}
public void setTemperature(int temperature) {
if (temperature < 0)
throw new IllegalArgumentException("can't be smaller than 0.")
this.temperature = temperature;
}
public void run() {
...
}
I don't recall a single case that a setter throws an exception as above. But I'm curious if it is good / bad.
The best approach is to make your object immutable, get rid of your setters and throws your exception in the constructor otherwise whatever the way you choose, in case of an error, you have a high risk to have your object in an inconsistent state which will cause hard bug to find. For a better understanding, please read this especially the section related to Failure Atomicity.