Java TimerTask 希望变量是最终的
无论如何,我试图制作类似聊天程序的东西,有人告诉我使用此代码来检查新消息,同时允许用户提交消息:
timer.schedule(new TimerTask() {
@Override
public void run() {
read.readChat(line);
}
}, 0, 1000);
//Wait for user input
while(true) {
String bar = scan.next();
}
其中 read.readChat(line);
是显示来自另一个文件的消息的方法。 Java告诉我,read
和line
都必须声明为final
...我不明白为什么特别是对于“line”
”因为这是一个变量,我需要改变它。
另外,在我将它们声明为最终版本后,我收到此错误:
unreported exception java.lang.Exception; must be caught or declared to be thrown
read.readChat(salt);
我做错了什么?
Anyway so im trying to make something like a chat program and someone told me to use this code to check for new messages while allowing the user to submit a message:
timer.schedule(new TimerTask() {
@Override
public void run() {
read.readChat(line);
}
}, 0, 1000);
//Wait for user input
while(true) {
String bar = scan.next();
}
Where the read.readChat(line);
is the method which displays the messages from another file. Java tells me that read
and line
both have to be declared as final
... I dont understand why especially for the "line
" because that's a variable and I need it to change.
Additionally after I declare them as final I get this error:
unreported exception java.lang.Exception; must be caught or declared to be thrown
read.readChat(salt);
What am I doing wrong?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
第二个错误告诉您,方法
read.readChat(line);
抛出一个checked
异常,因此您必须捕获。您不能在匿名
inner
类中使用在外部类中声明的局部变量。将它们设为final
或将它们声明为字段
(实例变量)。编辑:
Second error tells you that the method
read.readChat(line);
throws achecked
exception so you have to catch.You cannot use local variables declared at outer class in the Anonymous
inner
classes. Make themfinal
or declare them asfields
(instance variables).EDIT:
Cody,您希望将该异常抛出到哪个线程?现在计时器任务将在另一个线程(计时器的)中运行。那么,计时器线程将在您当前的设计中处理它。如果你只是想让运行重新抛出异常,你可以将其包装到 RuntimeException 中。
但是,对于 Timer 来说,它不会改变任何东西,因为 run() 方法是 Timer 线程最后看到的东西。如果您需要高级错误处理,则必须在 run() 内处理它。您能详细介绍一下您正在尝试做什么吗?
Cody, which thread do you want that exception to be thrown to? Right now the timer task is going to run in another thread (Timer's). So, is the timer thread that is going to deal with it in your current design. If you just want the run to re-throw an exception, you can wrap it to a RuntimeException.
But, for the Timer it is not going to change anything because the run() method is the last thing the Timer thread is going to see. If you need advanced an error handling, you have to deal with it inside run(). Can you tell a bit more about what you are trying to do?