异常以及任何处理异常初学


前言

对于一个程序员来说,我们会遇到一些异常(会导致程序中断的指令流),例如一个数不能除以0,在程序中这样会产生异常,为了使程序能够正常的运行下去,我们要处理异常


一.异常

异常分为受检异常和非受检异常,异常类下有许多子类,子类一些还有许多继承子类。
受检异常:就是写成代码会显示错误,有可能发生异常
非受检异常:只有运行时才显示异常,也叫运行时异常
Exception 范围最大的异常
IOException 传递指令不对,导致输入输出异常
RuntimeException 运行时异常,非受检异常

二、处理异常的两种方法

1.try-catch
2.throws

二、使用方法

1.try-catch

一般没有提示自己觉得有数据错误,可以当作if-else使用,做错误处理

代码如下(示例):

 public static void main(String[] args) {
    
    
        Scanner s = new Scanner(System.in);
        // 首先这里有两种错误,
        //1,是两个输入不是数字,
        //2是两个数字,除数为0
     	int a = s.nextInt();
     	int b = s.nextInt();  
        System.out.println(a/b);
    }
 try {
    
    
            int a = s.nextInt();
            int b = s.nextInt();
            System.out.println(a/b);
        }catch (Exception e){
    
    
        //实际上是InputMismatchException,
        //ArithmeticException,括号内可以写为InputMismatchException|ArithmeticException e
            System.out.println("输入异常");
        }

2.throws

传参参数异常,我们使用throws

代码如下(示例):

  public static void sum(String a,String b)throws IOException {
    
    
        int sum = Integer.parseInt(a)+Integer.parseInt(b);
        // 当然这是非受检异常,但这个方法没错,错误在于传入参数,把这个抛出去
   
    } 

3 , try - catch -finally

也是try-catch一种,只不过格式可以扩展成下面

try{
//可能发生异常的代码
}catch(异常情况(可以多个,可以一个)  参数值){
// 处理情况1,回调或者退出
}catch(异常情况 参数值){
// 处理情况2
}····{
}finally{
//必然执行代码,无论是否异常都要执行
}

举例

代码如下,

 public static void main(String[] args) {
    
    
        number n = new number();        // 生成实体类
        System.out.println( n(n).num); // 输出为20
          System.out.println(m(1));    // 输出为10
        
    }
   static class number{
    
    
        public int num;
    }
    static number n(number n){
    
    


        try {
    
    
            n.num= 10;
            return n;
        }catch ( Exception e){
    
    
        }finally {
    
    
            n.num = 20;
        }
        return n;
    }
     static  int m(int m){
    
    
        try {
    
    
            m= 10;
            return m; //如果去掉这行代码,输出为20
        }catch ( Exception e){
    
    
        }finally {
    
    
            m = 20;
        }
        return m;
    }

但是


总结

只是对异常及处理有初步的了解,至于更深的可能后续补充与扩展

猜你喜欢

转载自blog.csdn.net/m0_52063248/article/details/114380949
今日推荐