在java程序书写中难免毁掉用别人创建的方法那么我们怎么知道其中是否有异常呢,这时候就可以使用 throws关键字进行标记
举例如下:
public class Main{
public static void main(String[] args){
int c=divide(4,0);
System.out.println(c);
}
private static int divide(int a,int b)throws Exception {
return a/b;
}
}
在上例中,创建divide方法时使用throws关键字声明了此方法存在异常,若不进行处理将不能运行成功
处理办法如下:
public class Main{
public static void main(String[] args){
try{
int c=divide(4,0);
System.out.println(c);
}catch(Exception e){
System.out.println("捕获的异常信息为——"+e.getMessage());
}
}
private static int divide(int a,int b)throws Exception {
return a/b;
}
}
这样就可以运行成功!