2014-04-10 68 views
-1

嗯,我围绕我的返回语句在try catch块中,所以我可以确保输入的文本是字符串,因为该方法需要字符串返回,但是我仍然得到一个错误当它在那里时它需要一个return语句!为什么它仍然提示我缺少返回语句

public String getBatchName(){ 
    try { 
     return textField1.getText(); 
    } catch(InputMismatchException i){ 
     JOptionPane.showMessageDialog(
       null, "You have entered illegal characters for the batch name!" 
     ); 
    } 
} 

新代码:

public static String getBatchName(){ 
    try { 
     return textField1.getText(); 
    } catch(InputMismatchException i){ 
     JOptionPane.showMessageDialog(
       null, "You have entered illegal characters for the batch name!", "Error", JOptionPane.ERROR_MESSAGE 
     ); 
    } 
    return textField1.getText(); 
} 
+1

如果getText()中出现异常,它会返回什么? –

回答

2

如果一个异常被捕获你没有任何回报。在catch块之后包含另一个return语句,以处理发生异常并且其他return从未成功执行的情况。

+1

...或者只是不要捕捉异常,并让它传播开来。 –

+0

@rgettman我更新了我的第一篇文章,然后测试后输出这个代码函数吗? – Boolena

+0

@ Boolena:当然。如果到达最后一个返回语句将总是抛出一个'InputMismatchException',但是你的代码是有效的并且将被编译。 – Keppil

0

你将永远不会得到任何异常,同时呼吁JTextField#getText()

textField1.getText(); 

因此没有交给任何异常的点。

相关问题