day13_java异常处理

异常处理

生活中我们会根据不同的异常进行相应的处理,而不会就此中断我们的生活

public class TestException1 {

    public void a(){
        b();
    }
    public void b(){
        int x =5;
        int y = 0;
        int z = x / y;
        System.out.println(z);
    }
    public static void main(String[] args) {
    new TestException1().a();

    }


}

代码分析
image

异常的分类

image
一:Error 错误

二:Exception异常 (可以处理的)

1.运行时异常
    运行期出现的问题。
    可处理可不处理
    处理:后边的程序不会终端
2.非运行时的异常(受检异常)
    编译期提示的异常,必须处理

常见的异常类型

image



import java.lang.reflect.Field;
/**示例:常见异常*/
public class TestException2 {

    public static void main(String[] args) throws Exception, NoSuchFieldException, SecurityException {
        //异常
        //1  NullPointerException
        String s = null;//空对象

//      System.out.println(s.equals("hello"));
//      System.out.println(s.hashCode());
        //----------------Objects---------------------
//      System.out.println(Objects.equals(s, "hello"));
//      System.out.println(Objects.hashCode(s));
        //----------------------------------------------
        //2. InputMismatchException
//      Scanner input = new Scanner(System.in);
//      int n = input.nextInt();// int -> int
//      System.out.println(n);
        //3 ClassCastException
//      Object o = new String();
//      Integer i = (Integer)o;
        // 4. NumberFormatException
//      String str = "123a";
//      int n = Integer.parseInt(str);
//      System.out.println(n);
        //5. ClassNotFoundException
//      ClassLoader.getSystemClassLoader().loadClass("day13.B");
        //6.
        Class c = A.class;
        Field f = c.getDeclaredField("n");
//      f.setAccessible(true);
        Object o = c.newInstance();
        //6.  非法参数IllegalAccessException
        f.set(o , 22);
        System.out.println(f.get(o));
    }

}
class A{
    private int n;//私有的
}



异常处理

Java的异常处理是通过5个关键字来实现的:try、catch、 finally、 throw、throws

image

1.try-catch 块

选定代码,alt+shift+z能自动添加try-catch代码块

try{
  //会出现异常的代码块

}catch(异常类  对象){
  //处理异常
}

情况:
1. 无异常出现,try执行,catch不执行
2. 异常类型匹配,try块执行,catch执行
3. 异常类型不匹配,try执行,catch不执行

2.多重catch块

try{
  //会出现异常的代码块

}catch(异常类  对象){
  //处理异常
}catch(异常类  对象){
  //处理异常
}

异常块顺序:

  1. 由子类到父类
  2. 由普通到特殊

3.try -catch - finally

try{
  //会出现异常的代码块

}catch(异常类  对象){
  //处理异常
}finally){
  //一定会执行的代码,必须执行的代码;
  //通常时资源释放
}

System.exit(0);是唯一一种不执行finally块的情况,直接退出虚拟机

/**异常处理示例代码*/

import java.util.InputMismatchException;
import java.util.Scanner;

public class TestException3 {

    public void function(){
        Scanner input = new Scanner(System.in);
        System.out.println("输入两个数");
        try{
        int n1 = input.nextInt();
        int n2 = input.nextInt();
        int n3 = n1/n2;
        System.out.println("结果"+n3);
        //程序正常,就结束,不正常则往后执行;这是唯一一种不执行finally块的情况
        System.exit(0);//退出虚拟机
        }catch(ArithmeticException e){
            System.out.println("算数异常");
            System.out.println("出异常了,请与管理员联系");
        }catch(InputMismatchException e){
            System.out.println("输入类型异常处理");
            System.out.println(e);//展示异常字符串描述信息
            System.out.println(e.getMessage());//异常的消息
            e.printStackTrace();//异常的堆栈轨迹信息
        }catch(Exception e){
            System.out.println("一定能处理");
            //finally代码一定会执行
        }finally{
        System.out.println("释放资源");
        }
    }
    public static void main(String[] args) {
        TestException3 t3 = new TestException3();
        t3.function();
        System.out.println("后面还有代码 ");
    }

}

final,finally,finalize的区别
- final :修饰符 终态

修饰类,类不能被继承

修饰方法,方法不能被重写

修饰变量,变量不能修改,成为常量

  • finally:

异常处理,代码一定会执行的块

  • finalize:

方法。object类的方法。在释放对象之前,垃圾回收此对象之前调用此方法用于资源释放

throws声明异常

方法中的异常抛给了调用者,调用者的解决方式:

1.继续向上throws

2.try-catch处理

throw自己抛异常

自定义异常类

继承 一个系统异常类

/**自定义异常*/

class SexException extends Exception{

    private String str;

    public SexException(String str) {
        super();
        this.str = str;
    }

    @Override
    public String getMessage() {
        return str;
    }


}

class Person1{
    private String sex;

    public String getSex() {
        return sex;
    }

    public void setSex(String sex)  throws SexException{
        if(sex.equals("男") || sex.equals("女")){
            this.sex = sex;
        }else{
            throw new SexException("性别必须是男或者女");
        }

    }

}

public class Ex5 {

    public static void main(String[] args) throws SexException {
        Person1 zhangsan = new Person1();
        zhangsan.setSex("男");
        System.out.println(zhangsan.getSex());
    }

}

异常处理原则

  • 只用于处理非正常的情况
  • 避免过大的try
  • 使用多重catch
  • 不要忽略catch块中的异常
  • 改正代码
  • 文档声明

如何进行代码调试

  • 通过代码阅读
  • 加输出语句查找错误
  • 当程序结构越来越复杂时,需要专门的技术来定位和发现错去,就是”程序调试“

    步骤:1.猜测出错的代码的位置
          2.加断点
          3.单步运行:f5(单步跳入),f6(单步跳过)
          4.观察变量 
          5.发现问题 
          6.修正代码,重新运行 
          7.解决问题
    

猜你喜欢

转载自blog.csdn.net/qq_24135817/article/details/80561949