异常处理

Throwable
--Error
--Exception
异常处理
try{需要检测的代码} 发现异常
catch(异常类 变量){处理方式} 处理异常,能出来就不用抛出去不能就得抛,多个catch时,父类放在下面
finally{一定会执行的语句}通常适用于关闭资源
异常子父类体现,父类多个异常,子类只能抛其子集,子类出现异常不能在抛


多异常处理
声明异常建议声明具体
出现几个异常就对应几个catch块,不要多余
如果多个异常出现继承关系父类catch放在最下面


自定义异常
必须继承exception,不然没关系抛不了,因为异常类对象必须抛出
具备可抛性,只有throwwable体系中才能被throw和throws抛出


throw和throws区别:
throws定义在函数上,后面跟异常类用,隔开
throw定义在函数内,跟异常对象    单独存在下面就不要放语句执行不到
特殊子类异常runtimeexception运行时异常不需要声明,因为不需要呗调用者处理

当该异常发生程序会停止,对代码进行修正,所以不需要声明


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//,ArithmeticException, ArrayIndexOutOfBoundsException//在功能上通过throws关键字声明该功能可能出现问题
{
if(b<0)
throw new fushuexception("fdgdfg",b);
return a/b;
}
}
class exceptiondemo
{
public static void main(String[] args)//throws Exception
{
demo d = new demo();
try
{
int x = d.div(4,-1);
System.out.println("x="+x);
}
//catch (ArithmeticException e)//Exception e = new ArithmeticException
//{
// System.out.println("除零了");
//System.out.println(e.getMessage());//异常信息
//System.out.println(e.toString());//异常名称:异常信息
//e.printStackTrace();//调用虚拟机异常处理机制
//}


catch (fushuexception e)
{
System.out.println(e.toString());
System.out.println("错误数是:"+e.getvalue());
}
System.out.println("over");
}
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值