在我更好地学习Java的过程中,我一直在努力理解异常处理。我无法理解为什么以下代码无法编译。
编译器消息是:
try
在catch
块中,调用方法exTest.doExTest()。在这个方法中,我捕获一个InterruptedException,并在其 public class TestExceptionHandling {
public static void main(String argv[]) {
String output = "";
try {
output = "\nCalling method doExTest:\n";
exTest.doExTest();
}
catch (StupidException stupidEx) {
System.out.println("\nJust caught a StupidException:\n " + stupidEx.toString());
}
System.out.println(output);
}
}
class exTest {
static long mainThreadId;
protected static void doExTest() { //throws StupidException
mainThreadId = Thread.currentThread().getId();
Thread t = new Thread(){
public void run(){
System.out.println("Now in run method, going to waste time counting etc. then interrupt main thread.");
// Keep the cpu busy for a while, so other thread gets going...
for (int i = 0; i < Integer.MAX_VALUE; i++) {
int iBoxed = (int)new Integer(String.valueOf(i));
String s = new String("This is a string" + String.valueOf(iBoxed));
}
// find thread to interrupt...
Thread[] threads = new Thread[0];
Thread.enumerate(threads);
for (Thread h: threads) {
if (h.getId() == mainThreadId) {
h.interrupt();
}
}
}
};
t.start();
try {
Thread.sleep(5000);
}
catch (InterruptedException e){
System.out.println("\nAn InterruptedException " + e.toString() + " has occurred. Exiting...");
throw new StupidException("Got an InterruptedException ", e); // ("Got an InterruptedException. Mutated to StupidException and throwing from doExTest to caller...", e);
}
}
}
class StupidException extends Exception {
public StupidException(String message, Throwable t) {
super(message + " " + t.toString());
}
public String toString() {
return "Stupid Exception: " + super.toString();
}
}
块中抛出一个新的StupidException。
那么为什么编译器说它没有被抛出?我错过了什么?任何专家都可以帮我看看我的错误吗?
UNION ALL
答案 0 :(得分:2)
方法需要显式声明它们抛出异常(运行时异常除外,它们有点不同)。尝试将doExTest
方法声明为
protected static void doExTest() throws StupidException {
...
}