美文网首页
Java中异常和错误的区别及处理方式

Java中异常和错误的区别及处理方式

作者: 慕辙 | 来源:发表于2019-02-26 17:22 被阅读0次

    异常和错误的区别和联系

    在Java中,异常和错误同属于一个类:Throwable。异常和错误都是Java异常处理重要的类,且各自都包含大量子类。

    Exception(异常)是应用程序中出现的可预测,可恢复的问题,通常是轻度或中度的问题。异常通常是在特定环境下产生的,通常产生在特定的方法和操作中。例如程序使用readline方法时就可能产生IOException异常。

    Exception 类有一个重要的子类 RuntimeException。RuntimeException 类及其子类表示“JVM 常用操作”引发的错误。例如,若试图使用空值对象引用、除数为零或数组越界,则分别引发运行时异常(NullPointerException、ArithmeticException)和 ArrayIndexOutOfBoundException。

    Error(错误)大多表示运行应用程序时比较严重的错误。大多错误与编程者编写的程序无关,可能是代码运营时jvm出现的问题。例如,当 JVM 不再有继续执行操作所需的内存资源时,将出现 OutOfMemoryError。

    异常的处理方式

    异常的处理方式有两种一种是处理异常,一种是声明异常。

    处理异常的三个部件:try,catch,finally

    try块:放在try块的语句可能发生异常,编译器知道可能发生异常所以用一个特殊结构来处理这一块大的语句。

    catch块:catch块是try块产生异常的接收者,一旦产生异常,try块的运行中止。

    finally块:无论try块的运行结果如何,finally块的代码一定运行。所以在需要关闭某些资源时可以将关闭资源的代码放在finally块中用来清理代码。

    try-catch-finally规则:

    1. try 块后可同时接 catch 和 finally 块,但至少有一个块。
    2. 必须遵循块顺序:若代码同时使用 catch 和 finally 块,则必须将 catch 块放在 try 块之后。
    3. 一个 try 块可能有多个 catch 块。有多个catch块时执行第一个匹配块。

    下面的例子中使用了try,catch,finally:

    import java.io.BufferedReader;
    import java.io.IOException;
    import java.io.InputStreamReader;
    
    public class ExceptionHandleExamples {
        public static void main (String[] args){
            System.out.println("Enter input text to console:");
            InputStreamReader inputStreamReader = new InputStreamReader(System.in);
            BufferedReader inputReader = new BufferedReader(inputStreamReader);
            try{
                String inputText = inputReader.readLine();
                System.out.println("Read: "+inputText);
            }catch(IOException exc){
                System.out.println("Exception encountered: "+ exc );
            }finally{
                System.out.println("End.");
            }
        }
    }
    

    try块中readLine()可能产生IOException异常,try块可以检测这部分代码是否会产生异常,如果产生异常则交给catch块处理。最后不论try块的运行结果是什么,finally块都会运行输出"End. "。

    ** 异常声明 **
    以下示例如果数组的索引大于数组的长度则抛出数组越界异常。

    public int getNumberFromArray(int[] array, int index) throws ArrayIndexOutOfBoundsException {
            if (index > array.length) {
                throw new ArrayIndexOutOfBoundsException("数组越界异常");
            }
            return array[index];
        }
    

    几种常见异常的处理

    算术异常类:ArithmeticException

    public static void main (String[] args){
            int a = 1;
            int b = 0;
            try{
                int c = a/b;
            }catch(ArithmeticException e){
                System.out.println("发生了算术异常。");
            }
        }
    

    数组越界异常:ArrayIndexOutOfBoundsException

    public static void main (String[] args){
            int [] array = {1,2,12};
            try{
                System.out.println(array[5]);
            }catch(ArrayIndexOutOfBoundsException e){
                System.out.println("发生了数组越界异常。");
            }
        }
    

    类型强制转换异常:ClassCastException

    try{
                Object x = new String("String");
                System.out.println((Integer) x);
            }catch(ClassCastException e){
                System.out.println("类型强制转换异常");
            }
    

    数字格式异常 :NumberFormatException

    try{
                System.out.println(Integer.parseInt("it"));
            }catch(NumberFormatException e){
                System.out.println("数字格式异常");
    }
    

    输入输出异常:IOException

    import java.io.BufferedReader;
    import java.io.IOException;
    import java.io.InputStreamReader;
    
    public class ExceptionHandleExamples {
        public static void main (String[] args){
            System.out.println("Enter input text to console:");
            InputStreamReader inputStreamReader = new InputStreamReader(System.in);
            BufferedReader inputReader = new BufferedReader(inputStreamReader);
            try{
                String inputText = inputReader.readLine();
                System.out.println("Read: "+inputText);
            }catch(IOException exc){
                System.out.println("Exception encountered: "+ exc );
            }finally{
                System.out.println("End.");
            }
        }
    }
    

    相关文章

      网友评论

          本文标题:Java中异常和错误的区别及处理方式

          本文链接:https://www.haomeiwen.com/subject/ibaoyqtx.html