异常中的throw和throws,还有处理格式

来源:互联网 发布:web数据挖掘的分类 编辑:程序博客网 时间:2024/05/11 08:00
throws和throw的区别

1.throws使用在函数上,

throw使用在函数内.

2.throws后面跟的异常类.可以跟多个.用逗号隔开.

throw后面跟的是异常类的对象

异常处理格式:

   第一种格式:

try{

}catch(){

}

第二种格式:

try{

}catch(){

}finally{

}

第三种格式:

try{

}finally{

}

 

catch是用于处理异常.如果没有catch就代表异常没有被处理过,如果改异常时检测时异常,那么必须声明.

自定义的异常例子:对除数是0的异常进行处理

class ExceptionDemo1 {
public static void main(String[] args) {
Demo1 d = new Demo1();
try{
int x = d.div(4,-9);
System.out.println("x="+x);
}
catch(FuShuException e){ //捕捉异常,进行处理
System.out.println(e.toString());
}
System.out.println("over");
}
}


class FuShuException extends Exception {//自定义的异常类
FuShuException(String str){
super(str);
}
}


class Demo1 {
int div(int a,int b)throws FuShuException{
if(b < 0)
throw new FuShuException("出现了除数是负数的情况");//抛出异常
return a/b;
}
}
原创粉丝点击