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);
}
}
Related
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.
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 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
In Java, Foo.class.getMethod("bar") declares a checked exception of type NoSuchMethodException (among others).
What is the purpose of this exception? Isn't returning null sufficient to indicate that it was not found? What information or utility does throwing an exception add? Aside from forcing the user to explicitly be aware that it's possible for it to not be found, this seems superfluous. Returning null when something doesn't exist is a common pattern in Java, and this seems to be a prime candidate for that. So what was the reasoning behind this?
It appears that the designers of Java APIs made a distinction between situations when it's OK to ask for something that is missing and situations when you are supposed to ask only for things that exist.
They decided that asking for a missing key in a Map is OK, because the content of a map is something your program controls at runtime. Therefore, designers of the class library decided that it is unreasonable to ask programmers to check if a value is present before calling Map.get, and decided to return null instead.
The list of methods in a class, however, remains static at all times during a particular run, so it becomes reasonable to ask programmers to call getMethod only for methods that do exist. There are two consequences to this approach:
You can request multiple methods without checking each one - if you have a list of methods that must exist, for example, in a plugin component, you can get their Method reflection objects without checking the return value of individual getMethod calls, and
When you do not know if a method exists, call getMethods() - You can still examine all methods without knowing their names by getting a full list from the Class object.
Here is a code example to illustrate the first point. Current API lets you write this:
class Plugin {
private final Method init;
private final Method start;
private final Method stop;
public Plugin(Class cl) throws PluginException, SecurityException {
try {
init = cl.getMethod("init");
start = cl.getMethod("start");
stop = cl.getMethod("stop");
} catch (NoSuchMethodException ex) {
throw new PluginException("Plugin is missing a required method", ex);
}
}
...
}
instead of this:
class Plugin {
private final Method init;
private final Method start;
private final Method stop;
public Plugin(Class cl) throws PluginException, SecurityException {
init = cl.getMethod("init");
if (init == null) {
throw new PluginException("Plugin is missing init method");
}
start = cl.getMethod("start");
if (start == null) {
throw new PluginException("Plugin is missing start method");
}
stop = cl.getMethod("stop");
if (stop == null) {
throw new PluginException("Plugin is missing stop method");
}
}
...
}
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 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 6 years ago.
Improve this question
I have an object which in turn contains other objects. Now I have to iterate through this main object and then pick each object and then iterate through them to find out whether any empty fields are present in them. If the object itself is empty, I have to cut it out of main object. Any thoughts on this please.
public class Transactions {
private Integer totalTransactionCount = null;
private List<Transaction> transactionsList = new ArrayList<Transaction>();
}
public class Transaction {
private String amount = null;
private Foreign foreign = null;
}
public class Foreign {
private String amount = null;
private String commissionAmount = null;
private String exchangeRate = null;
}
Now I have a Transaction object with me and I have to loop throught each of its fields and in turn loop through their fields to find out any null/empty fields.
pseudo code for looping through a list of lists:
for each (innerList in outerList) do
if(innerlist.size == 0) then
//Code for removing empty inner lists.
else
for each ( object in innerList) do
//Check if objects are empty as well and remove it
end for
end if
end for
EDIT: Pointing out lack of research.
I would like to point out that you haven't really done your research properly, simply by googling iterate list of object as well as iterate list of list of object I got plenty of solutions.
Not to mention a question already asked here on Stack Overflow, please read the first answer of this post