public class TT implements Runnable
{
int b=100;
public synchronized void m1()throws Exception
{
b=1000;
Thread.sleep(5000);
System.out.println("b="+b);
} public void m2()
{
System.out.println(b);
}
public void run()
{
try
{
m1();
}catch (InterruptedException e)
{
e.printStackTrace();
}
}
public static void main(String[] args)throws Exception
{
TT tt=new TT();
Thread t=new Thread(tt);
t.start();
Thread.sleep(1000);
tt.m2();
}
}
m1()我明明抛出了异常,为什么运行是还报
unreported exception java.lang.Exception;must be caught or declared to be thrown m1()错误
{
int b=100;
public synchronized void m1()throws Exception
{
b=1000;
Thread.sleep(5000);
System.out.println("b="+b);
} public void m2()
{
System.out.println(b);
}
public void run()
{
try
{
m1();
}catch (InterruptedException e)
{
e.printStackTrace();
}
}
public static void main(String[] args)throws Exception
{
TT tt=new TT();
Thread t=new Thread(tt);
t.start();
Thread.sleep(1000);
tt.m2();
}
}
m1()我明明抛出了异常,为什么运行是还报
unreported exception java.lang.Exception;must be caught or declared to be thrown m1()错误
public void run()
{
try
{
m1();
}catch (InterruptedException e)
{
e.printStackTrace();
}
catch (Exception e)
{
e.printStckTrace();
}
都可以Class InterruptedException extends Exception
{
int b=100;
public synchronized void m1()throws Exception
{
b=1000;
Thread.sleep(5000);
System.out.println("b="+b);
} public void m2()
{
System.out.println(b);
}
public void run()
{
try
{
m1();
}catch (Exception e) //这个地方你出错了,因为你给的异常是不够的,所以保险起见,给一个父类异常即可。
{
e.printStackTrace();
}
}
public static void main(String[] args)throws Exception
{
TT tt=new TT();
Thread t=new Thread(tt);
t.start();
Thread.sleep(1000);
tt.m2();
}
}
刚才说错了,楼主可以看看,你的m1方法抛出的是Exception,但是你的run方法try{m1},抛出的却是InterruptedException,是不是这里错了呢? 这个解释是正确的。