在进行方法定义的时候如果要告诉调用者本方法可能产生哪些异常,
你就可以使用throws进行声明,如果该方法出现问题后不希望进行处理,就使用throws抛出。
范例:使用throws定义方法 (☆throws用在方法上)
class MyMath{
public static int div(int x,int y)throws Exception{
return x/y;
}
}
public class TestDemo {
public static void main(String[] args) {
// TODO 自动生成的方法存根
System.out.println(MyMath.div(10, 2));
}
} //未处理的异常类型 Exception
如果你现在调用了throws声明的方法,那么在调用时必须明确的使用try..catch进行异常捕获,因为该方法有可能产生异常捕获,因为该方法有可能产生异常,所以必须按照异常的方式来进行处理。主方法本身也属于一个方法,所以主方法也可以使用throws进行异常的抛出,这个时候如果产生了额一查
class MyMath{
public static int div(int x,int y)throws Exception{
return x/y;
}
}
public class TestDemo {
public static void main(String[] args) {
// TODO 自动生成的方法存根
try {
System.out.println(MyMath.div(10, 2));
}catch(Exception e) {
e.printStackTrace();
}
}
}
class MyMath{
public static int div(int x,int y)throws Exception{
return x/y;
}
}
public class TestDemo {
public static void main(String[] args)throws Exception {
System.out.println(MyMath.div(10, 2));
}
}
你们在以后所编写的代码里面一定要斟酌好可能产生的异常,因为面对未知的程序类,如果要进行异常的处理,就必须明确的指的有多少种异常。