异常的引入
Exception in thread “main” java.lang.ArithmeticException: / by zero
at com.sxt.day1217.exception1.Demo.main(Demo.java:12)
异常对象信息
1:具体异常类 java.lang.ArithmeticException
2:异常信息 / by zero
3:异常发生的地方:at com.sxt.day1217.exception1.Demo.main
4:异常发生的行数:Demo.java:12
如何解决?
1:切记:不要改变变量的值(尤其是用户提供的值)
2:做if…else… 判断 堵漏洞
问题1:漏洞太多,不太好补
问题2:业务代码和处理漏洞的代码放一块了,没有做到分层处理
3:使用java中的异常处理机制
它将异常处理代码和和业务代码分离,使程序更优雅,更好的容错性,高键壮性
提前预防代码出错,就算代码错了,也不会影响后续的代码正常执行
1:最好不要让代码出错
2:如果异常了怎么办:解决异常
异常的3个关键字 块代码 static{},if(){} else{},switch(){},for(){},try{},catch(){},finally{}
声明在块代码中的变量,不能在块的外面使用,如果要使用,必须在块的外面声明而且赋初始值
try:尝试着去运行有可能会出错的代码 ,把你认为有可能会出错的代码,放入try块中
catch:1 如果代码出错了,进入catch块,捕获异常对象
2 如果代码没有出错,不进catch块,正常运行
finally:表示最终的意思,无论什么情况,都会执行的意思
就算代码中有return语句,那么也会先把finally中的代码执行了,再return
但是:要把一种情况排除在外,JVM强制结束
finally一般做程序的扫尾操作,关闭流文件,关闭数据连接,关闭socket
try…catch…finally的组合方式
1.这3个都不能单独使用
2:try…catch…
3:try…finally…
4:try…catch…finally…
异常分类
Throwable
2个子类
Error, Exception
Exception
2个子类
RuntimeException:运行时异常
编译时异常(检查异常)
多重catch块
语法结构
try{
尝试运行代码
}catch(异常类型1 e){
e.printStackTrace();
}catch(异常类型2 e){
e.printStackTrace();
}catch(异常类型3 e){
e.printStackTrace();
}catch(异常类型4 e){
e.printStackTrace();
}…
注意:异常类型从具体到抽象(从子类到父类)
注意:不要把父异常写在钱,子异常写在后面,语法会报错,因为大异常会直接匹配这个具体异常,后面的catch块压根不会执行
了解:嵌套异常
try,catch,finally中都可以嵌套异常public static void main(String[] args) {
String s = null;
try {
System.out.println(s.length());
} catch (ArrayIndexOutOfBoundsException e) {
try{
}catch(ArrayIndexOutOfBoundsException e1){
try{
}catch(ArrayIndexOutOfBoundsException e2){
e2.printStackTrace();
}
e1.printStackTrace();
}
System.out.println("数组异常");
} catch(IndexOutOfBoundsException e){
System.out.println("下标异常");
} catch(RuntimeException e){
System.out.println("运行时异常");
} catch(Exception e){
System.out.println("异常");
}finally{
try{
}catch(Exception e){
}
}
System.out.println("正常执行");
}
写出5个常见的运行时异常
NullPointException 空指针异常
ArrayIndexOutOfBoundsException 数组下标越界
ArithmeticException:算术异常
InputMismatchException 类型匹配异常
StringIndexOutOfBoundsException 字符串下标越界public class Demo {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int d = 0;
try{
d = 100;
System.out.println("请输入第1个数");
int a = sc.nextInt();
System.out.println("请输入第2个数");
int b = sc.nextInt();
// System.out.println(d);
System.out.println(a/b);
//return;
System.exit(1); //JVM强制退出 一般参数为1即可
}catch(Exception e){
//System.out.println("进来?");
//System.out.println(e);
//System.out.println(e.toString());
e.printStackTrace(); //打印异常的堆栈信息
}finally{
System.out.println("我一定会执行");
}
//System.out.println("我可以执行吗");
//System.out.println(d);
}
}