class Excep
{
  int[] a=new int[]{1,2,3};
  void show()
  {
   System.out.println(a[4]);   throw new Exception();             //为什么这句会报错?而用下面的可以过    //throw new IndexOutOfBoundsException();  }
}class TestExcep
{
public static void main(String[] args)
{
Excep ec = new Excep();
try
{
ec.show();
}
catch (Exception e)
{
System.out.println("main fun exception:" + e);
}
}
}

解决方案 »

  1.   

    throw new Exception();             //为什么这句会报错?而用下面的可以过
    你这样写就是故意抛出一个异常,
    当然会报错的
    如果用catch(Exception e)的话
    那是捕捉异常
    如果有异常才执行的
    呵呵
      

  2.   

    throw new Exception();             这也是故意抛出一个异常,但不报错
      

  3.   

    Exception 分为需要检查的异常和不需要检查的异常(也称运行时异常)运行时异常继承自RuntimeException,而普通异常直接继承自Exception对于普通异常,需要catch或者在方法中声明
    对于运行时异常,则不需要显式的catch或者声明IndexOutOfBoundsException 这里正好是一个运行时异常
      

  4.   

    1 System.out.println(a[4]);这行数组越界了呀
    2 (//为什么这句会报错?而用下面的可以过)的意思是编译错误吗
      他的意思是show函数里会抛出异常(throw new Exception();就是这句显式抛出的)
      处理这个异常有两种方法
      一 把show函数声明称void show() throws Exceptionclass Excep
    {
      int[] a=new int[]{1,2,3};
      void show() throws Exception
      {
       System.out.println(a[4]);   throw new Exception();               //throw new IndexOutOfBoundsException();  }
    }class TestExcep
    {
    public static void main(String[] args)
    {
    Excep ec = new Excep();
    try
    {
    ec.show();
    }
    catch (Exception e)
    {
    System.out.println("main fun exception:" + e);
    }
    }
    }   二 在函数中处理这个异常用try catchclass Excep
    {
      int[] a=new int[]{1,2,3};
      void show()
      {
       System.out.println(a[4]);               try
                   {
      throw new Exception();           
                   }
                   catch(Exception e)
                   {
                        System.out.println("show fun exception" + e);
                   }    //throw new IndexOutOfBoundsException();  }
    }class TestExcep
    {
    public static void main(String[] args)
    {
    Excep ec = new Excep();
    try
    {
    ec.show();
    }
    catch (Exception e)
    {
    System.out.println("main fun exception:" + e);
    }
    }
    }以上两种方法都能顺利编译通过