可以忽略“catch”条款吗?我有这个代码,我想做的是扫描包含特定字符串的所有单词并将它们存储在String res中。
但是我现在的代码不会遍历循环,因为它会在“catch”子句中断时停止。有没有办法忽略catch子句,让“try”继续循环直到它到达文件末尾?
String delimiter = " - ";
String[] del;
String res = new String();
if(curEnhancedStem.startsWith("a"))
{
InputStream inputStream = getResources().openRawResource(R.raw.definitiona);
try {
BufferedReader in = new BufferedReader(new InputStreamReader(inputStream));
String s = in.readLine();
while(s != null)
{
s = in.readLine();
del = s.split(delimiter);
if (del[0].contains(curEnhancedStem))
{
res = res + s + "\n\n";
}
}
return res;
}
catch (Exception e) {
// nothing to do here
}
}
答案 0 :(得分:3)
如果你真的希望它继续在内循环上,即使出现错误,你可以在那里放置另一个try块。
String delimiter = " - ";
String[] del;
String res = new String();
if(curEnhancedStem.startsWith("a"))
{
InputStream inputStream = getResources().openRawResource(R.raw.definitiona);
try {
BufferedReader in = new BufferedReader(new InputStreamReader(inputStream));
String s = in.readLine();
while(s != null)
{
try {
s = in.readLine();
del = s.split(delimiter);
if (del[0].contains(curEnhancedStem))
{
res = res + s + "\n\n";
}
}
catch (Exception e) {
// Error in string processing code (as opposed to IO) - Don't care... Continue
}
}
}
return res;
}
catch (Exception e) {
// nothing to do here
}
}
另一个想法是使用更具体的异常 - 而不仅仅是普遍捕获所有异常
答案 1 :(得分:2)
我认为你必须在内部获得异常,所以试试这个。
try {
BufferedReader in = new BufferedReader(new InputStreamReader(inputStream));
String s = in.readLine();
while(s != null)
{
try{
s = in.readLine();
del = s.split(delimiter);
if (del[0].contains(curEnhancedStem))
{
res = res + s + "\n\n";
}
} catch(Exception e){
// Do Something
}
}
return res;
}
catch (Exception e) {
// nothing to do here
}
}
如果你得到异常,它将在循环中处理,但你的循环将继续。
答案 2 :(得分:1)
您的catch
条款中没有任何内容。尝试为while
循环添加类似下面的内容(将其保留在try
块中)以找出您获得的exception
:
catch(Exception e)
{
Log.e("Exception here: "+ e.getMessage());
}