package test03_1;
public class Demo12_声明和捕获 {
public static void main(String[] args)throws Exception//在调用者上继续声明,可以声明多个异常
{
Demo12 d = new Demo12();
try
{
d.show(0000);
}
catch (Exception e)//对方抛出了什么问题就在括号里定义什么问题的引用
{
System.out.println("yixchandndsjd");
}
}
}
class Demo12
{
// 如果定义功能时发生问题需要报告给调用者,可以通过函数上使用throw关键字进行声明
void show(int x)throws Exception
{
//声明和捕获
//声明
// 声明就是将问题标识出来,报告给调用者
// 如果函数内通过throw抛出了编译时异常而捕获,那么必须通过throws进行声明,让调用者经行处理
//捕获
/*
* try
* {
//需要被检测的语句
* }
* catch(异变类 变量)//参数
* {
//异常处理的语句
* }
* finally
* {
//一定会被执行的语句
* }
*/
if(x!=0)
throw new Exception();
else
System.out.println(“show run”);
}
}
实例+throw以及throws区别
package test03_1;
public class 实例01 {
public static void main(String[] args) {
Rec r = new Rec(-3, 4);
int area =r.getArea();
System.out.println("Area="+area);
}
}
@SuppressWarnings(“serial”)
class NoValueException extends RuntimeException
{
NoValueException()
{
super();
}
NoValueException(String message)
{
super(message);//建立异常信息
}
}
class Rec
{
private int length ;
private int width ;
Rec(int length,int width)
{
if(length<=0||width<=0)
{
//抛出异常,不用声明,不需要调用者处理。一旦问题发生,就让调用者修改代码
throw new NoValueException("含有非法数值");
}
this.length = length;
this.width = width ;
}
public int getArea()
{
return length*width;
}
}
/*
* throw与throws的区别:
* throw用在函数内 用于抛出的异常对象
* throws用在函数上 用于进行异常类的声明,后面的异常类可以是多个,用逗号隔开
*/