在这个方法中,我在哪里可以使用return语句?里面终于?还是试试?
我对在try catch语句中返回字符串感到有点困惑。
这是我的代码。
public List<String> getEmailAddr(String strAccountnbr, String strCode) throws Exception {
String strQuery2 = null;
ResultSet rs = null;
PreparedStatement ps = null;
try
{
List<String> emailAddress= new ArrayList<String>();
strQuery2 = "SELECT c.EmailAddress AS EmailAddress" +
" FROM customeremailid c " +
"WHERE c.AccountNbr = ? " +
"AND c.Code = ? ";
logMsg("strQuery2: "+strQuery2);
ps = getDBConn().prepareStatement(strQuery2);
ps.setString(1, strAccountnbr);
ps.setString(2, strCode);
rs = ps.executeQuery();
while(rs.next())
{
emailAddress.add((rs.getString("EmailAddress")));
}
}
catch(Exception e)
{
e.printStackTrace();
}
return emailAddress;
}
我收到错误emailAddress cannot resolved to a variable.
有什么帮助吗?
答案 0 :(得分:0)
我收到错误,因为
emailAddress
无法解析为变量。任何 帮助
List<String> emailAddress= new ArrayList<String>();//Declare it outside the block
try{...
OR 在外部声明,但在try
内初始化,以便在catch
块中访问它。
List<String> emailAddress=null;
try{...
emailAddress= new ArrayList<String>();//Initialize it inside the block
现在您的emailAddress
只能在try{//Block}
中访问,但不能在catch{//Block}
中访问
答案 1 :(得分:0)
将您的代码更改为
List<String> emailAddress= new ArrayList<String>();
try
{
....
}
return emailAddress;
以前,您尝试返回的变量仅限于try块范围。
答案 2 :(得分:0)
return
可以在try
块内部或try - catch
块之外使用,finally
块基本上用于放弃不用于写入返回语句的资源。
答案 3 :(得分:0)
public List<String> getEmailAddr(String strAccountnbr, String strCode) throws Exception {
String strQuery2 = null;
ResultSet rs = null;
PreparedStatement ps = null;
List<String> emailAddress= new ArrayList<String>();
try{
strQuery2 = "SELECT c.EmailAddress AS EmailAddress" +
" FROM customeremailid c " +
" WHERE c.AccountNbr = ? " +
" AND c.Code = ? ";
logMsg("strQuery2: "+strQuery2);
ps = getDBConn().prepareStatement(strQuery2);
ps.setString(1, strAccountnbr);
ps.setString(2, strCode);
rs = ps.executeQuery();
while(rs.next())
{
emailAddress.add((rs.getString("EmailAddress")));
}
}
catch(Exception e)
{
//some error especify your exception or uses a generic..
throw new EmailAdressException("BLA BLA BLA...")
}
//if everything is fine return email
return emailAddress;
}
答案 4 :(得分:0)
您需要考虑范围。在您的代码中,当您在块(try-block)中声明您的emailAddress时,emailAddress仅在该块内可用。 try-catch仅适用于在执行查询时处理可能的异常。尝试将try-catch限制为仅引发异常的代码(在这种情况下,您可以/应该重构代码,以便查询在其自己的方法中完成)。
如果在try-catch块之外声明emailAddress,则在catch块之后返回它。
public List<String> getEmailAddr(String strAccountnbr, String strCode) throws Exception {
List<String> emailAddress= new ArrayList<String>();
try {
// Handle query here
} catch(Exception e) {
// You should not catch Exception, but a more fine-grained exception.
// In this case, SQLException
}
return emailAddress;
}