小白学Java,用throws解决异常
package Example24;
/*
- 用throws解决异常:
- 1.定义方法时用throws直接抛出
- public static int divide(int x,int y) throws Exception{
int result =x/y;
return result;
} - 2.主方法中处理异常
- public static void main(String[] args) {
try {
int result=divide(4,2);
System.out.println(result);
}catch(Exception e){
System.out.println(“捕获的异常的类型:”+e.getMessage());
e.printStackTrace();//打印捕捉的异常信息
}
finally {
System.out.println(“进入finally代码块”);
}
}- 3.特别注意:当用throws抛出异常时,如果有错误程序会中止运行
- */
public class Example24 {
public static void main(String[] args) {
try {
int result=divide(4,2);
System.out.println(result);
}catch(Exception e){
System.out.println(“捕获的异常的类型:”+e.getMessage());
e.printStackTrace();//打印捕捉的异常信息
}
finally {
System.out.println(“进入finally代码块”);
}
}
public static int divide(int x,int y) throws Exception{
int result =x/y;
return result;
}
}
divide(4,2)给定数字正常代码运行结果:
2
进入finally代码块
divide(4,0)给定数字异常代码运行结果:
捕获的异常的类型:/ by zero
java.lang.ArithmeticException: / by zero
at Example24.Example24.divide(Example24.java:38)
at Example24.Example24.main(Example24.java:27)
进入finally代码块