Method Exit Method

Is there any way to exit the method? I heard that there are two ways out.

One: throw Exception.

public void dosomething() { if(...) { throw new MyException(); } // there might be another process. } 

Two: return some value. Even the void method, we can return a value.

 public void dosomething() { if(...) { return; } // there might be another process. } 

Question: is there a better way?

+4
source share
4 answers

Technically, you could System.exit(int) (the int value would be the value returned from the process, and probably nonzero to indicate an error). However, this is a little cruel.

You can also interrupt yourself.

 Thread.currentThread().interrupt(); 

But:

  • this is still an exception. You are not throwing it explicitly, but still the result of InterruptedException
  • your thread must do some I / O in the future to register this interrupt. If it is exclusively computational, then because of this it will not work.

eg. (pay attention to sleep() to catch the interrupt):

 public class Test { public static void method() throws Exception { Thread.currentThread().interrupt(); Thread.sleep(100); System.out.println("method done"); } public static void main(String[] args) throws Exception { method(); System.out.println("done"); } } 

gives me:

 Exception in thread "main" java.lang.InterruptedException: sleep interrupted at java.lang.Thread.sleep(Native Method) at T.method(T.java:5) at T.main(T.java:9) 
+3
source

There is a third, though not very useful, method:

 System.exit(0); 

If you ask this question for academic purposes ...

The fact that you throw an exception does not necessarily mean that you exit the method. For example, if you do this:

 try { throw new Exception(); // ... } catch (Exception e) { // ... } 

you will not exit the method.

Also, if you call the void method, it will exit (implicit) after the last statement in the method body.

+1
source

you can use

 Thread.currentThread().stop(); 

It will terminate the current thread without stopping the entire JVM.

BUT

stop() method is deprecated and inherently unsafe. From the specification:

This method is inherently unsafe. Stopping a thread using Thread.stop forces it to unlock all monitors that it has blocked (as a natural consequence of an uncontrolled ThreadDeath exception up the stack). If any of the objects previously protected by these monitors were in an inconsistent state, damaged objects became visible to other threads, potentially leading to arbitrary behavior.

So, if you need to exit the method and cannot return or throw exeption, try running this method in your thread and terminate this thread if necessary. Please note that this is not a standard procedure, but most of the hacking.

+1
source

Can this be considered?

  public void test(){ System.out.println("Do My work"); String s = null; s.length(); System.out.println("Do My other work"); } 
0
source

Source: https://habr.com/ru/post/1446181/


All Articles