2013-04-27 67 views
-3

我正在寻找退出方法的方法, 我发现了两种方法 System.exit(); 退货;哪个是退出方法的最佳方式

System.exit() - 退出完整程序 返回退出当前方法并返回其余代码无法访问的错误。

class myclass 
{ 
    public static void myfunc() 
    { 
     return; 
     System.out.println("Function "); 
    } 
} 

public class method_test 
{ 
    public static void main(String args[]) 
    { 
     myclass mc= new myclass(); 
     mc.myfunc(); 
     System.out.println("Main"); 
    } 
} 
+0

退出杀死整个程序。返回只是离开了当前的方法。 – 2013-04-27 18:00:17

+0

你的代码杀死了一个优秀的程序员,因为return语句已经用在代码其余部分的顶部我的意思是如果你在代码之前使用了这个代码,那么代码的其余部分将会变得无法访问 – 2013-04-27 18:13:11

+0

就我个人而言,我来自一个思想流派。一个入口,一个出口。每个非void方法应该有一个'return'语句,它应该是方法中的最后一个语句。这使得该方法更容易理解和阅读,因为您不可能错过隐藏在您不期待的某个逻辑分支深处的“return”语句,但这只是我 – MadProgrammer 2013-04-27 19:23:40

回答

2

部分没有最好的方式,这取决于形势。

理想情况下,根本没有必要退出,它只会返回。

int a() { 
    return 2; 
} 

如果确实需要退出,使用退货,这样做没有惩罚。

void insertElementIntoStructure(Element e, Structure s) { 
    if (s.contains(e)) { 
     return; // redundant work; 
    } 
    insert(s, e); // insert the element 
} 

这是最好避免使用尽可能多的,因为这是不可能的测试失败的空隙在功能

避免system.exit,这是一个应该留给只能使用一个主要副作用主要。

void not_a_nice_function() { 
    if (errorDetected()) { 
     System.exit(-1); 
    } 
    print("hello, world!"); 
} 

这个伪代码是邪恶的,因为如果你试图重用这段代码,很难找到使它过早退出的东西。

+0

但返回语句后的剩余代码导致发生错误method_test.java:6:error:unreachable statement System.out.println(“Function”); – RajaSekar 2013-04-27 18:08:14

+0

只有在过早收益是无条件的情况下才会发生。如果有条件的话,java会认识到它可以被达到。 – Dmitry 2013-04-27 18:10:29

+0

基本上,你需要做一个if语句,否则java很聪明,代码永远不会到达(由于无条件跳转)。 – Dmitry 2013-04-27 18:12:18

3

退出方法的最佳和正确的方法是添加return statement

System.exit()将关闭您的程序。

如果您使用system.exit线程一旦进入,它将不会回来。

system.exit是Design of the Shutdown Hooks API

+1

但在return语句后留下的代码导致错误 method_test。java:6:error:unreachable statement System.out.println(“Function”); – RajaSekar 2013-04-27 18:03:35

+0

@downvoter。请留心留下评论,以便我可以改进我的帖子。 – 2013-04-27 18:06:39

+0

@RajSekar如果你使用system.exit一旦线程去那里,它不会回来。 – 2013-04-27 18:08:08

2

首先你的代码会杀死好的程序员想象这段代码Which is the Best way to exit a method这段代码例子说明了如何在System.out.print()之前返回一个返回值;因为,如果你想确切地退出你的整个应用程序,而 命令

  return; 

成为return语句LOLS 命令

  System.exit(int status); (status=0 for Normal Exit && status=-1 for abnormal exit 

仅用于Unreachable后用来脱身从/回报 这两种方法在操作上有所不同