public class SearchForExceptionHandler
{
   public static void main(String[] args)
   {
      try
      {
         
         System.out.println("Method main called");
         methodA();
      }
      
      catch(MyException e)
      {
         System.out.println("Exception caught in Main");
      }
   }
   
   static void methodA()
   {
      System.out.println("Method A called");
      methodB();
   }
   
   static void methodB()
   {
      System.out.println("Method B called");
      methodC();
   }
   
   static void methodC()
   {
      System.out.println("Method C called");
      new MyException();
   }
}
class MyException extends Throwable
{
   public MyException()
   {
      System.out.println("Exception thrown in MyException");
   }
}编译时出现下面的问题
E:\Java\JavaLab\Chapter12\SearchForExceptionHandler.java:16: exception MyException is never thrown in body of corresponding try statement
      catch(MyException e)
      ^
1 error不知道什么原因? 请教

解决方案 »

  1.   

    你只是创建了一个异常对象,并没有抛出异常,因此catch语句不能捕获我也是刚学,不知道理解的对不对,等待大虾指正
      

  2.   

    try
          {
             
             System.out.println("Method main called");
             methodA();
          }
    这段代码中没有异常会抛出,所以不需要用try
      

  3.   

    如果你想看到异常的话,可以参考下面的代码public class SearchForExceptionHandler
    {
       public static void main(String[] args)
       {
          try
          {
             
             System.out.println("Method main called");
             methodA();
          }
          
          catch(MyException e)
          {
             System.out.println("Exception caught in Main");
          }
       }
       
       static void methodA() throws MyException
       {
          System.out.println("Method A called");
          methodB();
       }
       
       static void methodB() throws MyException
       {
          System.out.println("Method B called");
          methodC();
       }
       
       static void methodC() throws MyException
       {
          System.out.println("Method C called");
          throw new MyException();
       }
    }
    class MyException extends Throwable
    {
       public MyException()
       {
          System.out.println("Exception thrown in MyException");
       }
    }
      

  4.   

    这是输出的结果Method main called
    Method A called
    Method B called
    Method C called
    Exception thrown in MyException
    Exception caught in Main
      

  5.   

    谢谢楼上的,原来自己敲代码时忘了对每个方法 throws MyException, 所以编译时会报错