所以这是我在编程过程中遇到的最奇怪的事情。是的,我不是编程专家,但我边走边学。我有一个应用程序与服务器通信,主线程中有一个套接字,读取是在一个单独的类和线程中完成的,并使用 asynctask 在一个单独的类中写入。
问题是位置管理器。我可以很好地与服务器交谈并写入/读取命令,我实现了 LocationManager 及其侦听器。
然后我开始实现一种方法,用 locatinChanged 上的新坐标更新我的 textview。到目前为止,一切都很好。事情是当我在 eclipse 中使用 Emulator 控件并发送坐标时,应用程序因 stringOutOfBoundsException 而崩溃(我已经编程了 3 年,现在从未见过这种情况)。我查看了通过它的代码等等。阅读 stacktrace、logcat、console 和我能想到的任何地方,但它让我无处可去。直到我终于去了看起来像这样的读者线程:
public class ReaderThread extends Thread {
public void run() {
new Thread(new Runnable(){
public void run(){
try {
//Establish a bufferedreader to read from the socket/server.
in = new BufferedReader(new InputStreamReader(socket.getInputStream()), 8 * 1024);
}
catch(Exception e) { e.printStackTrace(); }
//As long as connect is true.
while (connected) {
String line;
try {
//Try to read a line from the reader.
line = in.readLine();
System.out.println(in.readLine());
if (in == null) {
//No one has sent a message yet.
System.out.println("No data recieved");
}
else {
int i = 0;
//As long as someone is sending messages.
while((line = in.readLine()) != null ){
//Make a new Message.
Message msg;
msg = new Message();
//Set the object to the input line.
msg.obj = line;
//Set an id so it can be identified in the main class and used in a switch.
msg.what = i;
System.out.println("i is: "+i);
//Send the message to the handler.
Main.this.h.sendMessage(msg);
}
}
}
catch (Exception e) {
System.out.println(e.getMessage());
}
}
}
}).start();
}
变量 i 位于 if 语句中,具体取决于服务器发送的内容,但我将其删除,因为它与此问题无关。
问题是该死的捕获。当捕获为 IOException 时,应用程序崩溃。运气不好,我将其更改为 Exception 并打印 e.message 以捕获错误并查看导致错误的原因。事情是这个变化修复了它。如何将 IOException 切换为普通的 Exception 来解决这样的问题?
就像 IOException 程序说:“嘿,你不会捕捉到错误,但没有错误”,但是 Exception 它说“现在你可以捕捉到它,所以我会继续”。
我的应用程序正在运行,但我无法理解这一点,为什么以及如何发生这种情况?