Java 将异常捕获到线程的外侧
我需要捕捉线程运行时发生的异常Java 将异常捕获到线程的外侧,java,java-me,jakarta-ee,Java,Java Me,Jakarta Ee,我需要捕捉线程运行时发生的异常 我试图抛出新的异常,但它显示了一个错误,“未报告的异常……必须被捕获或声明为抛出”。2 如果不可能,为什么? 如果你能解释原因 这是我的密码 try { log("Connecting to Module.."); int no = searchdevices.getSelectedIndex(); String Selectaddress = searchdevices.getStrin
我试图抛出新的异常,但它显示了一个错误,“未报告的异常……必须被捕获或声明为抛出”。2 如果不可能,为什么? 如果你能解释原因 这是我的密码
try {
log("Connecting to Module..");
int no = searchdevices.getSelectedIndex();
String Selectaddress = searchdevices.getString(no);
String name = Selectaddress.substring(0, 6);
String add = Selectaddress.substring(Selectaddress.indexOf("$") + 1);
if (no == -1) {
Alert al = new Alert("Warning", "" + no, null, AlertType.WARNING);
al.setTimeout(3000);
display.setCurrent(al);
}
final String fdata2 = "btspp://" + add + ":1;master=false;encrypt=false;authenticate=false";
finalurl = fdata2;
fbtname = name;
// fbtadd = add;
new Thread(new Runnable() {
public void run() {
try {
isConnOpen = true;
stream = (StreamConnection) Connector.open(fdata2);
in = stream.openInputStream();
out = stream.openOutputStream();
url2 = fdata2;
GoTo_Success();
} catch (IOException ex) {
throw new Exception();//in side exception
}
}
}).start();
} catch (Exception e) {
log("Please switch on bluetooth and then try again"); // want to catch here..
}
谢谢。当您在catch中抛出新异常时,您必须使用try..catch来处理它 试试这个:
new Thread(new Runnable() {
public void run() {
try {
isConnOpen = true;
stream = (StreamConnection) Connector.open(fdata2);
in = stream.openInputStream();
out = stream.openOutputStream();
url2 = fdata2;
GoTo_Success();
} catch (IOException ex) {
try {
throw new Exception();
} catch (Exception e) {
e.printStackTrace();
}//in side exception
}
}
}).start();
必须使用throws子句在方法声明中声明异常,然后才能使用
throw new exception()代码>
如果您看到Thread.run()
,您将发现没有抛出异常
子句。因此,您将得到一个编译错误
请参阅以下链接:
好吧,假设一个线程在代码运行的同时运行,它怎么能捕获异常呢?一旦调用start(),线程就会启动(很可能是在调用之后的某个时间点),程序的其余部分将继续运行,超过捕获
例如,线程是在一个名为“foo”的方法中创建和启动的。一旦开始,foo方法就会到达末尾并返回到调用它的任何对象。然后调用一个方法“bar”。此时,新线程实际上被安排运行,因此“bar”方法被挂起,线程中的run方法被执行。现在例外情况发生了。这个计划离你想要达到的目标还很远。即使不是这样,程序的一部分也处于休眠状态。如果您想得到另一个线程中异常的通知,您必须手动传输异常
一个例子是使用队列
或类似的东西,您的工作线程将捕获任何出现的异常并将其添加到队列中
“主线程”(或特殊的异常处理程序线程,或UI线程,或…)将定期轮询队列,查看是否存在任何新异常,如果存在,则可以将其显示给用户。向我们显示您试图抛出异常的代码。是的,但在“}”行下面还有另一个捕获。start();“,我想抓住那个例外。我在评论中提到过。@Nirav:您可能无法在那里获得它,因为您正在创建一个新的可运行类,并在其中重写run方法。所以所有的异常都应该只在那个类中处理。是的,你是对的。我们不能处理过去,只能处理现在或将来。我说的对吗?看看java.util.concurrent包()。我想你可以说现在/将来的一点。