try...catch的使用
没有try…catch,程序执行出现了异常,程序会停止执行之后的代码;
如果有了try…catch,程序的出现的异常会被捕获和处理,异常之后的代码仍能继续执行。
一、没有try…catch
package com.exception.test;
import java.util.Scanner;
public class TryCatch {
public static void main(String[] args) {
Scanner sc=new Scanner(System.in);
int a,b,c;
a=sc.nextInt();
b=sc.nextInt();
c=a%b;
System.out.println("余数为:"+c);
System.out.println("程序继续执行");
}
}
结果:
二、有try…catch
try…catch 包围快捷键 Ctrl+Alt+T
package com.exception.test;
import java.util.Scanner;
public class TryCatch {
public static void main(String[] args) {
Scanner sc=new Scanner(System.in);
int a,b,c;
try {
a=sc.nextInt();
b=sc.nextInt();
c=a%b;
System.out.println("余数为:"+c);
} catch (Exception e) {
e.printStackTrace();
}
System.out.println("程序继续执行");
}
}
结果: