【发布时间】:2013-06-22 12:56:36
【问题描述】:
我在 LogCat 中收到 OutOfMemoryError 消息,我的应用程序崩溃了,因为这些错误未被捕获。
OutOfMemoryError 有两个原因:
1. 将大文本文件读入字符串。
2. 将该字符串发送到我的 TextView。
简单地在这两件事上添加一个 catch 不仅可以捕获 OutOfMemoryError,而且似乎可以完全解决内存不足的问题。
LogCat 中不再出现崩溃和错误消息。该应用程序运行完美。
这怎么可能?到底发生了什么?
使用此代码,我收到错误消息和应用程序崩溃:
try
{
myString = new Scanner(new File(myFilePath)).useDelimiter("\\A").next();
}
catch (FileNotFoundException e)
{
e.printStackTrace();
}
myTextView.setText(myString);
只需“捕获”OutOfMemoryError,LogCat 中就不会再出现错误消息,也不会崩溃:
try
{
myString = new Scanner(new File(myFilePath)).useDelimiter("\\A").next();
}
catch (FileNotFoundException e)
{
e.printStackTrace();
}
catch(OutOfMemoryError e)
{
}
try
{
myTextView.setText(myString);
}
catch(OutOfMemoryError e)
{
}
【问题讨论】:
-
查看日志在 OutOfMemoryError 捕获块中添加 e.printstacktrace
-
同意@Droider。您看不到错误消息,因为您没有像以前那样打印它们。
标签: java android try-catch out-of-memory