Java——异常——throws关键字
用throws关键字对外声明该方法有可能发生异常。
语法格式:
修饰符 返回值类型 方法名([参数1,参数2,...])throws
ExceptionType1[,ExceptionType...]{
}
案例1:
//异常 throws关键字
public class Abnormal04 {
public static void main(String[] args) {
//下面的代码定义了一个 try...catch语句用于捕获异常
try{
int result=divide(4,2); //调用方法
System.out.println(result);
}catch (Exception e){ //对异常进行处理
// System.out.println("捕获异常信息为:"+e.getMessage());
e.printStackTrace(); //打印捕获的异常信息
}
}
//下面的方法实现了两个整数相除,并使用 throws关键字声明抛出异常
public static int divide(int x,int y) throws Exception{
int result = x/y;
//定义一个变量 result记录两个数相除的结果
return result; //将结果返回
}
}
当在调用方法时,如果不知道如何处理声明抛出的异常,也可以使用throws关键字继续将异常抛出,这样程序也能编译通过,但需要注意的是,程序一旦发生异常,如果没有被处理,程序就会非正常终止。
案例2:
//异常 throws关键字02
public class Abnormal05 {
public static void main(String[] args) throws Exception{
int result=divide(4,0); //调用方法
System.out.println(result);
}
//下面的方法实现了两个整数相除,并使用 throws关键字声明抛出异常
public static int divide(int x,int y) throws Exception{
int result = x/y;
//定义一个变量 result记录两个数相除的结果
return result; //将结果返回
}
}