java的异常处理是通过5个关键字来实现:try,catch,finally,throw,throws。
try,catch,finally
//public class test {
// public static void main(String[] args) {
// try {
// int num1 = 12;
// int num2 = 0;
// System.out.println("两个数的商为:" + num1 / num2);
// }catch(Exception ex){
// System.out.println("你的程序出错了");
// }
// System.out.println("");
// }
//}
public class test {
public static void main(String[] args) {
try {
int num1 = 12;
int num2 = 0;
System.out.println("两个数的商为:" + num1 / num2);
}catch(InputMismatchException ex){
System.out.println("你的程序出错了");
}finally {
System.out.println("继续执行文件");
}
}
}
throw\throws
抛出异常
throw和throws区别:
(1)位置不同:
throw:方法内部
throws:方法的签名处,方法的声明处
(2)内容不同:
throw+异常对象throws+异常的类型
(3)作用不同:
throw:异常出现的源头,制造异常。
throws: 在方法的声明处,告诉方法的调用者,这个方法中可能会出现我声明的这些异常。然后调用者对这个异常进行处理:要么自己处理要么再继续向外抛出异常。
public class test1 {
public static void main(String[] args) {
devide();
}
//提取一个方法,两个数相除
public static void devide() throws Exception {
int num1 = 12;
int num2 = 3;
if(num2 == 0){
//人为制造异常
// try {
// throw new Exception();
// } catch (Exception e) {
// e.printStackTrace();
// }
// System.out.println("try-catch处理异常");
throw new Exception();//抛出异常
}
else{
System.out.println("两个数的商是:" + num1/num2);
}
}
}