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);
}
}
}
你这样写就是故意抛出一个异常,
当然会报错的
如果用catch(Exception e)的话
那是捕捉异常
如果有异常才执行的
呵呵
对于运行时异常,则不需要显式的catch或者声明IndexOutOfBoundsException 这里正好是一个运行时异常
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);
}
}
}以上两种方法都能顺利编译通过