Demo12_声明和捕获(包含throw以及throws区别)+实例

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用在函数上 用于进行异常类的声明,后面的异常类可以是多个,用逗号隔开
*/

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值