读书人

异常抛出的问题

发布时间: 2014-01-26 14:39:47 作者: rapoo

异常抛出的问题:
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);
}
}
}


------解决方法--------------------------------------------------------
throw new Exception(); //为什么这句会报错?而用下面的可以过


你这样写就是故意抛出一个异常,
当然会报错的
如果用catch(Exception e)的话
那是捕捉异常
如果有异常才执行的

------解决方法--------------------------------------------------------
Exception 分为需要检查的异常和不需要检查的异常(也称运行时异常)

运行时异常继承自RuntimeException,而普通异常直接继承自Exception

对于普通异常,需要catch或者在方法中声明
对于运行时异常,则不需要显式的catch或者声明

IndexOutOfBoundsException 这里正好是一个运行时异常
------解决方法--------------------------------------------------------
1 System.out.println(a[4]);这行数组越界了呀
2 (//为什么这句会报错?而用下面的可以过)的意思是编译错误吗
他的意思是show函数里会抛出异常(throw new Exception();就是这句显式抛出的)
处理这个异常有两种方法
一 把show函数声明称void show() throws Exception

class 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 catch

class 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)         

读书人网 >Java Exception

热点推荐