return 只能用在有返回類型的函數(shù)中,但是有返回值的函數(shù)一定要有return嗎?return都可以用在函數(shù)的哪些地方呢?這是本文需要討論的問題。 例一: class test { public String test() {
if(true){
return "";
}
else{
return "";
}
}
} 上面這樣即可通過編譯,但是下面這兩個例子卻不能通過編譯:
(一)
class test {
public String test() {
if(true){
return "";
}
}
}
(二)
class test {
public String test() {
if(isTrue()){
return "";
}
else if(!isTrue()){//兩個if里的判斷包括了所有的可能性,但是還是編譯期error
return "";
}
}
boolean isTrue(){
return true;
}
}
結(jié)論1: 對于(一),這是因為java編譯器認(rèn)定單獨的if語句只在當(dāng)一定條件滿足情況下才執(zhí)行,它認(rèn)為if不會有任何情況下都能執(zhí)行的能力。 對于(二),這是因為java編譯器對if else 語句能夠全面囊括所有情況的能力只限定在的if...else(或if...else if...else)時,而不包括if...else if。
例二: class test {
public String test() {
while(true){
return "";
}
}
}
上面這樣即可通過編譯,但是下面這樣不行:
class test {
public String test() {
while(isTrue()){
return "";
}
}
boolean isTrue(){
return true;
}
}
結(jié)論2: 這是因為編譯器認(rèn)為while語句有在任何情況下都能執(zhí)行的能力,但是只在入?yún)閠rue的情況下有該能力。
例三: public class test {
String test() throws Exception{
throw new Exception();//拋出異常后,跳出程序,程序中止
}
} 結(jié)論3: 如果函數(shù)中創(chuàng)建了異常,并拋出,則該函數(shù)可以不返回值。
|