java 可以在 switch 语句中使用 throw 代替 break 吗?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/16579585/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Can throw be used instead of break in a switch statement?
提问by Jerry
Can throw also be used to exit switch statement without using break keyword? Why use a throw instead of break?
不使用break关键字也可以用throw退出switch语句吗?为什么要使用 throw 而不是 break?
switch(number)
{
case 1:
throw new RuntimeException("Exception number 1");
case 2:
throw new RuntimeException("Exception number 2");
}
回答by Makoto
There are two cases in which you could use a throw
to interrupt the flow of a switch:
在两种情况下,您可以使用 athrow
来中断交换机的流程:
Flow Control; in general, this is a badpractice - you don't want exceptional behavior deciding where your program decides to go next.
Unlikely-but-plausible default case; in case you hit a condition in which reaching the default shouldbe impossible, but happens anyway. Somehow. Miraculously. Or, if you have strict coding standards, which mandate that switch statements have a default case.
Example:
public class Test { public static enum Example { FIRST_CASE, SECOND_CASE; } public void printSwitch(Example theExampleCase) { switch(theExampleCase) { case FIRST_CASE: System.out.println("First"); break; case SECOND_CASE: System.out.println("Second"); break; default: // should be unreachable! throw new IllegalStateException( "Server responded with 724 - This line should be unreachable"); } }
流量控制;一般来说,这是一个不好的做法 - 您不希望异常行为决定您的程序决定下一步去哪里。
不太可能但合理的默认情况;如果你打在达到预设的条件应该是不可能,却发生了。不知何故。奇迹般地。或者,如果您有严格的编码标准,要求 switch 语句具有默认情况。
例子:
public class Test { public static enum Example { FIRST_CASE, SECOND_CASE; } public void printSwitch(Example theExampleCase) { switch(theExampleCase) { case FIRST_CASE: System.out.println("First"); break; case SECOND_CASE: System.out.println("Second"); break; default: // should be unreachable! throw new IllegalStateException( "Server responded with 724 - This line should be unreachable"); } }
回答by Claude
I see some reasons for throw in a switch statement.
我看到了抛出 switch 语句的一些原因。
1st: not instead of a break but as the body of the default
case. Consider the following example where a switch is defined on an enumeration:
第一:不是代替休息而是作为default
案件的主体。考虑以下示例,其中在枚举上定义了开关:
pubic enum E {
A,
B
}
The switch as of the time as it is first written looks like:
首次编写时的开关如下所示:
E e = ...;
switch (e) {
case A:
...
break;
case B:
...
break;
default:
throw new IllegalStateException("Unknown enumeration value " + e);
}
The throw is a fallback for future extensions to the enumeration E
.
throw 是对枚举的未来扩展的后备E
。
2nd: Sometimes I have where small getter functions, for example in the Swing table model. There I use return instead of break;
第二:有时我有 where 小的 getter 函数,例如在 Swing 表模型中。在那里我使用 return 而不是 break;
public String getColumnName(int col)
{
switch (col)
{
case 0: return "Column 0";
case 1: return "Column 1";
...
This is for the sake of brevity or compactness. One may say that these returns break the control flow. This is true. However, I think that for compactness reasons it might be allowed here.
这是为了简洁或紧凑。有人可能会说这些返回破坏了控制流。这是真实的。但是,我认为出于紧凑性原因,这里可能允许这样做。
If you accept return
instead of a break
in this case you may accept throw
too here.
如果您在这种情况下接受return
而不是 a break
,您也可以throw
在这里接受。
Object[] x = ...; // get some array which is not null from a function which
// only returns arrays, e.g. OSGI services
switch (x.length)
{
case 0: throw new IllegalArgumentException("No service defined");
case 1: return x[0]; // return the only available service
default:
... // evaluate all services and return the best matching one
return x[...];
}
回答by Alpesh Gediya
You can use throw
in switch
block but its not good coding/design practice. throw
is meant to control exceptional/error situation in code not for controlling execution of instructions.
您可以throw
在switch
块中使用,但它不是很好的编码/设计实践。throw
旨在控制代码中的异常/错误情况,而不是用于控制指令的执行。
Eventhough you can use throw
in switch
, I would recommded not to use it in switch
. :)
尽管您可以使用throw
in switch
,但我建议您不要在switch
. :)
回答by Juned Ahsan
You are talking about only one scenario, where you need to throw the exception. switch is designed to run a case and break it. If it is in a method and if you only use throw then how will you return a value from that method? In simple terms throw will return the method but break will not. You can continue running your code after the switch with break but not with throw.
您只讨论了一种情况,即您需要抛出异常。switch 旨在运行一个案例并打破它。如果它在一个方法中,如果你只使用 throw 那么你将如何从该方法返回一个值?简单来说,throw 将返回该方法,但 break 不会。您可以在使用 break 切换后继续运行您的代码,但不能使用 throw。
回答by Evgeniy Dorofeev
break is used to prevent falling thru to the next case, when you throw an exception there will be no falling thru
break 用于防止掉到下一个 case,当你抛出异常时不会掉到
case 1:
throw new UnsupportedOperationException();
break; <-- compile error, unreachable code
It typically makes sense to throw an exception in otherwise clause
在 else 子句中抛出异常通常是有意义的
switch (op) {
case 1:
// do something
break;
...
default:
throw new UnsupportedOperationException();
}
回答by WebServer
There are few problems using throw instead of break;
使用 throw 而不是 break 几乎没有问题;
1)when you throw some Exception the execution of rest of the function stops.
1)当您抛出一些异常时,其余函数的执行将停止。
ie:
IE:
int m=0;
switch (m) {
case 0:
y=10;
break;
case 2:
y=11;
break;
default:
break;
}
System.out.println(y);//this y will never be printed if Exceptions are thrown
2) Exceptions generally represent some error condition,and switch not every time should create exception.
2)异常一般代表一些错误情况,不是每次切换都应该创建异常。
3) To get the value "Exception number 1" from
3) 从
throw new RuntimeException("Exception number 1");
you have to wright catch block and call e.getMessage();
你必须使用 catch 块并调用 e.getMessage();
like:
喜欢:
catch(RuntimeException e){
String str=e.getMessage();
}
this is even more overhead and also the data you can pass is only String Object.
这是更多的开销,而且您可以传递的数据只是字符串对象。
Conclusion:- Its better to use normal break.
结论:-最好使用正常休息。
回答by imran001
throw Can not be used instead of break in a switch statement. because throw is just used for exceptions while switch is used for conditional purposes...
throw 在 switch 语句中不能用来代替 break。因为 throw 仅用于异常,而 switch 用于条件目的......