throws和throw的区别
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;
}
}
异常处理格式:
1.throws使用在函数上,
throw使用在函数内.
2.throws后面跟的异常类.可以跟多个.用逗号隔开.
throw后面跟的是异常类的对象
第一种格式:
try{
}catch(){
}
第二种格式:
try{
}catch(){
}finally{
}
第三种格式:
try{
}finally{
}
catch是用于处理异常.如果没有catch就代表异常没有被处理过,如果改异常时检测时异常,那么必须声明.
class ExceptionDemo1 {自定义的异常例子:对除数是0的异常进行处理
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;
}
}