try中的代码段是可能异常的代码段,catch用于捕捉try中代码段的错误将处理,finally表示不论异常与否,都要执行的代码。throws是声明程序可能会有异常,当调用有throws声明的方法时,必须使用try...catch来捕捉异常,尽管可能没有异常。
public class Example24{
public static void main(String[] args){
try{
int result=divide(4,0);//调用divide方法,用4除0,会报by zero的异常错误
System.out.println(result);
}catch(Exception e){//定义一个变量e,类型为Exception,异常专用类
System.out.println("捕获的异常为:"+e.getMessage());//获取到异常并打印
return;//有异常后,结束当前语句
}finally{
System.out.println("不管是否有异常,都会进入finally代码块");//不论是否有异常,都执行finally中的语句。如果catch中没有return,程序还能继续向下执行
}
System.out.println("程序继续向下执行……");
}
public static int divide(int x,int y){
int result=x/y;
return result;
}
}
public class Example25{
public static void main(String[] args){
try{
int result=divide(4,0);//尽管4/2并不会报错,但由于调用的方法divide声明了此处可能会有异常,因此,也必须使用try...catch,否则编译不过
System.out.println(result);
}catch (Exception e){
e.printStackTrace();//打印异常的固定写法。但本段没有对程序做任何处理,只是打印出来,因此如果当异常发生时,程序中终止运行
}
}
public static int divide(int x,int y) throws Exception{//在参数后,通过throws Exception声明此方法可能会有异常
int result=x/y;
return result;
}
}