throw:
抛出一个异常对象两种处理:
1.使用try-catch捕获处理异常
2.将异常抛出并且在方法中声明
throws:将异常抛给调用的方法
区别:
位置不同
throw
产生于方法体内
throws在方法声明处
作用不同:
throw 产生并抛出异常,原则是谁调用谁处理
throws:
声明当前方法有异常产生,调用者在调用当前方法的时候,需要进行异常处理
数量不同:
throw 只能产生一个异常对象
如果不做处理的结果会有:
抛出一个异常对象两种处理:
1.使用try-catch捕获处理异常
2.将异常抛出并且在方法中声明
throws:将异常抛给调用的方法
区别:
位置不同
throw
产生于方法体内
throws在方法声明处
作用不同:
throw 产生并抛出异常,原则是谁调用谁处理
throws:
声明当前方法有异常产生,调用者在调用当前方法的时候,需要进行异常处理
数量不同:
throw 只能产生一个异常对象
throws 可以声明多个异常类用","隔开
public void divide(int num1,int num2){
int re;
re = num1/num2;
System.out.println(re);
}
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
int num1 = in.nextInt();
int num2 = in.nextInt();
new test().divide(num1, num2);
如果不做处理的结果会有:
那么我们就使用try-catch
Scanner in = new Scanner(System.in);
try{
int num1 = in.nextInt();
int num2 = in.nextInt();
new test().divide(num1, num2);
}catch(ArithmeticException e){
System.out.println("0不能做除数");
}catch (InputMismatchException e) {
System.out.println("输入格式不正确");
}finally {
System.out.println("--------------finally-------------");
}
最后我们看看thows和throw
public static void main (String[] args)throws Exception {
Scanner in = new Scanner(System.in);
try{
int num1 = in.nextInt();
int num2 = in.nextInt();
new test().divide(num1, num2);
throw new Exception("不能被0除");
}