'捕获'OutOfMemoryError完全解决了内存不足的问题?

Eri*_*ass 5 java android try-catch out-of-memory

我在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);
Run Code Online (Sandbox Code Playgroud)



只是通过"捕获" 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)
{
}
Run Code Online (Sandbox Code Playgroud)

Tom*_*Tom 1

如果您捕获 OutOfMemoryError,垃圾收集器会尝试释放先前使用的内存,因此如果应用程序让垃圾收集器完成其工作(即应用程序不再引用您的大字符串),则应用程序可以继续运行)。

然而,捕获 OutOfMemoryError 远非万无一失。请参阅捕获 java.lang.OutOfMemoryError?