首页 > 技术文章 > JAVA异常处理

hzau-xpgao 2020-10-27 21:08 原文

本篇博客主要讲述一下问题:

1、JAVA Error类与Exception类的区别

2、异常处理的两种方式,并举例说明

3、选取RuntimeException类的五个子类,编写抛出并捕获上述子类异常的程序

4、自定义一个异常类,并在某场景下抛出该异常对象

---------------------------------------------------------------------------------------------------------------------

问题1:

Error类是所有错误类的祖先, Exception类是所有异常类的祖先

区别:Error类不是程序需要捕获和处理的,当Error发生时,程序将会停止。

           而异常发生时,虚拟机系统根据异常的类型,产生相应的异常对象,程序应对这些异常对象进行相应的处理。

问题2:

   异常处理的两种方式:抛出和捕获处理

             抛出分为隐式抛出和显示抛出,下面举例说明。

 隐式抛出:   

package First.unit4;
import java.util.*;
public class Exception {
    public static void main(String[] args) {
        Stack s=new Stack();
        Object ob=s.pop(); 
        String foo=args[1];
        System.out.println("foo = "+foo);
    }
}

上述代码会发生以下异常:

 

 

 

 上述代码发生隐式异常,但编译通过。

显示抛出:

package First.unit4;
import java.io.*;
public class Exception {
    public static void main(String[] args)throws IOException {
        BufferedReader in=new BufferedReader(new InputStreamReader(System.in));
        String c1;
        String[] e=new String[10];
        int i=0;
        while(i<10){
            c1=in.readLine();
            e[i]=c1;
            i++;
        }
        
    }
    
}

上述代码如果不加 “throws IOException”,程序不能编译通过。

故隐式抛出不写抛出可以正常编译,而显示抛出不写抛出不可以正常编译


 

问题3:RuntimeException类(运行时异常类)的部分子类:  

   1、NullPointerException

   2、EmptyStackException

        3、IndexOutOfBoundsException

   4、ClassCastException

   5、ArithmeticException


NullPointerException example:

class Exception {
        public static void main(String[] args) {
            Run r1=new Run(1, 2, 3);
            Run r2=null;
            r1.print();
            r2.print();
        }
       
}
class Run{
        private int a;
        private int b;
        private int c;
        public Run(int a, int b, int c) {
                this.a=a;
                this.b=b;
                this.c=c;
        }
        public void print() {
                System.out.println("a="+a+" b="+b+" c="+c);
        }
}

上述代码运行后会发生空指针异常,如下图:

 

 发生异常的原因是引用r2是空引用,不指向任何一个对象,故调用的方法为空方法,会发生空指针异常。

 改正方法:1、让引用r2指向一个具体对象

                 2、捕捉异常,加入如下所示代码即可

try{ 
      r2.print();
}
catch (NullPointerException r) {
      System.out.println("NullPointerException");
}

 

EmptyStackException example:

import java.util.Stack;
class Exception {
        public static void main(String[] args) {
            Stack s=new Stack();
            Object ob=s.pop();
            
        }
}

上述代码运行后会发生以下异常:

 改正方法:

import java.util.Stack;
class Exception {
        public static void main(String[] args) {
            Stack s=new Stack();
            Object ob=s.push(s);
            ob=s.pop();
        }
}

 

IndexOutOfBoundsException example:

class Exception {
        public static void main(String[] args) {
               int[] array= {1,2,3,4,5,6,7,8,9};
               int a=array[-1];
               System.out.println("a="+a);
        }
}

上述代码运行后会发生如下异常:

 

 改正方法:访问数组下标应该在0~arrary.length之间。

 

ClassCastException example:

abstract class Animal {
      abstract void kind();
}
class Tiger extends Animal {
    public void kind() {
        System.out.println("肉食");
    }
    
}
class Horse extends Animal {
    public void kind() {
        System.out.println("草食");
    }
   
}
class Exception {
    public static void main(String[] args) {
        Animal a = new Tiger();
        a.kind(); 
        Tiger t = (Tiger) a;
        t.kind();
        Horse h=(Horse) a;
        h.kind();
    }
}

上述代码运行后,会发生以下错误:

 改正方法:运用instanceof运算符  

if (a instanceof Tiger) {
      Tiger t = (Tiger) a;
      t.kind();
}
else if (a instanceof Horse) {
       Horse h=(Horse) a;
       h.kind();
}

加入上述语句后,不会再发生异常


ArithmeticException example:

class  Except{
      public static void main(String[] args) {
              int a, b, c;
              a=6; b=0; c=0;
              c=a/b;
              System.out.println("c="+c);
      }
}

 

上述代码运行后 ,有如下错误:

 

 改正方法:使用“try catch"语句捕捉异常。

try {
    c=a/b;
} 
catch (Exception e) {
    System.out.println("ArithmeticException");
}

 

 问题4:

public class SelfGenerateException extends Exception{
        SelfGenerateException(String msg){
               super(msg);  
       }
        static void throwOne() throws SelfGenerateException{
                int a = 1;
                if (a==1){
                        throw new SelfGenerateException("a为1");
                }        
        }
       public static void main(String args[]){
        try{
                throwOne();
        }
        catch(SelfGenerateException e){
                e.printStackTrace();
        }
    }
}

程序说明:1、“throw new 异常类”的作用往往是根据程序的需要而定义流程的跳转。

     2、“throw new 异常类”只是主动产生异常对象,至于这个对象如何处理,

需要看当时的环境——声明抛出还是捕获处理

(注:对于问题4,由于本人(小白)也没有看懂,只能给出书中的例子。)


 

以上就是我对JAVA异常处理的一些理解,如有错误,欢迎指正。

推荐阅读