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()错误

解决方案 »

  1.   

    m1()直接抛Exception,在调用它时你就要捕获Exception,如果m1里用try catch就不用在调用的时候捕获你添加的那个throw的Exception了
      

  2.   

    用throw exception就是告诉别人我会抛出错误哦,别人看见了,在使用的时候为了防止错误肯定要catch你那个exception,而在方法里用try catch的话,别人不知道你这里面会有异常,因此不会去catch.
      

  3.   


    public void run() 

      try 
        { 
          m1(); 
        }catch (InterruptedException e) 
          { 
            e.printStackTrace(); 
          } 
          catch (Exception e) 
         {
            e.printStckTrace();   
        }
      

  4.   

    刚才说错了,楼主可以看看,你的m1方法抛出的是Exception,但是你的run方法try{m1},抛出的却是InterruptedException,是不是这里错了呢?
      

  5.   

    Exception > InterruptedException如果开始 throws InterruptedException or 后来的 catch(Exception e) 
    都可以Class InterruptedException extends Exception
      

  6.   

    你的代码异常抛错了。应该是: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 (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(); 
      } 
        
      

  7.   

    引用 5 楼 pingchangxinli 的回复:
    刚才说错了,楼主可以看看,你的m1方法抛出的是Exception,但是你的run方法try{m1},抛出的却是InterruptedException,是不是这里错了呢? 这个解释是正确的。