简体   繁体   中英

Java - How to exit a method without return what he is expecting?

I've a method similar to the one bellow, where I want to return a private variable of one class only and only if, some conditions are verified. Otherwise I want to exit the method without return anything. I've tried something like the code bellow but I'm afraid that returning null is not a good idea. Are there any way to exit a method like the break keyword works for cycles?

private Classxpto classxpto;

public Classxpto getclassxpto(String abc, Date asd){
        String curr_abc= classxpto.getabc();
        Date curr_asd= classxpto.getasd();
            if("my conditions"){
                //dont return classxpto
                return null;
            }else if("my other conditions"){
                classxpto.setabc(abc);
                classxpto.setasd(asd);
                return classxpto;
            }
            return null;    
    }

You can either return null (or some default Classxpto instance) or throw an exception. Throwing an exception is the only way to exit a method having a non-void return type without returning anything.

You cannot return "nothing" from a method unless it is declared as a void method. (And in that case, you can only return "nothing"!)

The Java Language Specification says this in §14.17 :

A return statement with an Expression must be contained in one of the following, or a compile-time error occurs:

  • A method that is declared to return a value
  • ....

If you have no value to return, then your choices are either to pick some value that means (to your application) "no value", or throw an exception.

  • The value null is often used to signify "no value", but you can use other things ... depending on the declared return type.

  • Throwing an exception would a bad whay to deal with this, unless "no result" is truly an exceptional outcome. Using exceptions and exception handling for normal flow control is a considered to be bad design in Java, and is liable to lead to serious performance problems.

It is also theoretically possible to terminate the JVM by calling System.exit(...) , or write the method so that it runs forever or goes to sleep forever. However these are most likely "undesirable" behaviours.

You can always throw the Exception

if(conditionNotMet){

throw new YourCustomException();

}

then Handle it in whichever way you want !!!!

A method either return nothing (void), or something (including null ), but can throw an Exception .

You have to think about how clients of the class will use the method. An exception really mean that the no return case should not occur in normal conditions.

Assuming the method is in a Foo class:

public class Foo {

   private ClassXPto classXPto;

   public ClassXPto getClassXPto() {...}

   // other Foo stuff
}

In the client code:

Returning null

Foo foo; // initialized somewhere    
ClassXPto x = foo.getClassXPto("abc", new Date());
if (x != null) {
   // do something with x
}

Throwing/catching an exception

Foo foo; // initialized somewhere    
try {
   ClassXPto x = foo.getClassXPto("abc", new Date());
   // do something with x
}
catch (WhatEverExceptionYouChoose e) {
   // process the exception
}

Propagating an exception

Foo foo; // initialized somewhere    
ClassXPto x = foo.getClassXPto("abc", new Date());
// do something with x. This point will be reached only
// if there is no exception thrown by getClassXPto()

If your method is designed in such a way that the return parameter is optional, you could use the new Optional mechanisms in Java 8.

Instead of returning null you would return Optional.empty().

For more information visit https://docs.oracle.com/javase/8/docs/api/java/util/Optional.html

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM