黑马程序员技术交流社区
标题:
在异常中出现了throw和throws,有什么区别吗?
[打印本页]
作者:
张宝
时间:
2013-3-16 17:04
标题:
在异常中出现了throw和throws,有什么区别吗?
本帖最后由 张宝 于 2013-3-16 18:07 编辑
在异常中有个throws意思是抛出异常,在自定义异常中又出现个throw,也是抛出异常,有什么区别吗?
作者:
123
时间:
2013-3-16 17:46
Throws在方法签名中使用,用于声明该方法可能抛出的异常。
Throw在函数内使用,用于抛出一个实际的异常。
作者:
HM刘博
时间:
2013-3-16 17:50
本帖最后由 HM刘博 于 2013-3-16 17:53 编辑
throws关键字通常应用在方法上,用来指定可能跑出的异常,多个异常要用逗号隔开,当在主函数中调用该方法时,如果发生异常,就会将异常抛给指定异常对象
class Demo
{
int div(int a,int b)throws ArithmeticException,ArrayIndexOutOfBoundsException<FONT color=red>//在功能上通过throws的关键字声明了该功能有可能会出现问题</FONT>。
{
int[] arr = new int[a];
System.out.println(arr[4]);
return a/b;
}
}
class ExceptionDemo2
{
public static void main(String[] args) //throws Exception
{
Demo d = new Demo();
try
{
int x = d.div(5,0);
System.out.println("x="+x);
}
catch (ArithmeticException e)
{
System.out.println(e.toString());
System.out.println("被零除了!!");
}
catch (ArrayIndexOutOfBoundsException e)
{
System.out.println(e.toString());
System.out.println("角标越界啦!!");
}
System.out.println("over");
}
}
复制代码
throw关键字通常用在方法体中,并且抛出一个异常对象。程序在执行到throw语句时立即停止,它后面的语句都不执行。通过throw抛出异常后,如果想在上一级代码中来捕获并处理异常,则需要在抛出异常的方法中使用throws关键字在方法声明中指明要跑出的异常;如果要捕捉throw抛出的异常,则必须使用try—catch语句。
class FuShuException extends Exception
{
private int value;
FuShuException()
{
super();
}
FuShuException(String msg,int value)
{
super(msg);
this.value = value;
}
public int getValue()
{
return value;
}
}
class Demo
{
int div(int a,int b)throws FuShuException
{
if(b<0)
throw new FuShuException("出现了除数是负数的情况------ / by fushu",b);//<FONT color=red>手动通过throw关键字抛出一个自定义异常对象。
</FONT>
return a/b;
}
}
class ExceptionDemo3
{
public static void main(String[] args)
{
Demo d = new Demo();
try
{
int x = d.div(4,-9);
System.out.println("x="+x);
}
catch (FuShuException e)
{
System.out.println(e.toString());
System.out.println("错误的负数是:"+e.getValue());
}
System.out.println("over");
}
}
复制代码
欢迎光临 黑马程序员技术交流社区 (http://bbs.itheima.com/)
黑马程序员IT技术论坛 X3.2