java学习笔记12--异常处理-阿里云开发者社区

开发者社区> 开发与运维> 正文
登录阅读全文

java学习笔记12--异常处理

简介:

1、异常处理概述

从一个读取两个整数并显示商的例子:

public static void main(String args[])
{
    Scanner input = new Scanner(System.in);  
    System.out.print("Enter two integers: ");
    int number1 = input.nextInt();
    int number2 = input.nextInt(); 
    System.out.println(number1 + " / " + number2 + " is " + (number1 / number2));
 }

Enter two integers: 3 0

Exception in thread "main" java.lang.ArithmeticException: / by zero
at Main.main(Main.java:18)

解决的一个简单的办法是添加一个if语句来测试第二个数字:

public class Main
{
    public static void main(String args[])
    {
        Scanner input = new Scanner(System.in);
        
        System.out.print("Enter two integers: ");
        int number1 = input.nextInt();
        int number2 = input.nextInt();
        if(number2 != 0)
            System.out.println(number1 + " / " + number2 + " is " + (number1 / number2));
        else
            System.out.println("Divisor cannot be zero ");
    }
}

为了演示异常处理的概念,包括如何创建、抛出、捕获以及处理异常,继续改写上面的程序如下:

public class Main
{
    public static void main(String args[])
    {
        Scanner input = new Scanner(System.in);
        
        System.out.print("Enter two integers: ");
        int number1 = input.nextInt();
        int number2 = input.nextInt();
        try {
            if(number2 == 0)
                throw new ArithmeticException("Divisor cannot be zero");
            System.out.println(number1 + " / " + number2 + " is " + (number1 / number2));
        }
        catch(ArithmeticException ex) {
            System.out.println("Exception: an integer " + "cannot be divided by zero ");
        }
        System.out.println("Execution continues ...");
    }
}

2、异常处理的优势

改用方法来计算商:

public class Main
{
    public static int quotient(int number1, int number2) {
        if(number2 == 0)
            throw new ArithmeticException("Divisor cannot be zero");
        return number1 / number2;
    }
    
    public static void main(String args[])
    {
        Scanner input = new Scanner(System.in);
        
        System.out.print("Enter two integers: ");
        int number1 = input.nextInt();
        int number2 = input.nextInt();
        try {
            int result = quotient(number1, number2);
            System.out.println(number1 + " / " + number2 + " is " + result);
        }
        catch(ArithmeticException ex) {
            System.out.println("Exception: an integer " + "cannot be divided by zero ");
        }
        System.out.println("Execution continues ...");
    }
}

异常处理的优势就是将检测错误从处理错误中分离出来。

3、异常类型

 4、关于异常处理的更多知识

java的异常处理模型基于三种操作:声明一个异常、抛出一个异常、捕获一个异常

声明异常

在方法中声明异常,就是在方法头中使用关键字throws,如下所示:

public void myMethod throws Exception1,Exception2,……,ExceptionN

抛出异常

检测一个错误的程序可以创建一个正确的异常类型的实例并抛出它

实例:

IllegalArgumentException ex = new IllegalArgumentException("Worng Argument");
throw ex;

或者直接:

throw new IllegalArgumentException("Worng Argument");

捕获异常

当抛出一个异常时,可以在try-catch中捕获和处理它:

try {
    statements;
} catch (exception1 ex1){
    handler for exception1;
} catch (exception1 ex2){
    handler for exception2;
} 
……
catch (exception1 exN){
    handler for exceptionN;
}
    

从异常中获取信息

可以采用Throwable类中的方法获取异常的信息

public class test {
    public static void main(String[] args) {
        try {
            System.out.println(sum(new int[]{1,2,3,4,5}));
        } catch(Exception ex) {
            ex.printStackTrace();
            System.out.println(ex.getMessage());
            System.out.println(ex.toString());
            System.out.println("Trace Info Obtained from getBackTrace");
            StackTraceElement[] traceElements = ex.getStackTrace();
            for(int i = 0; i < traceElements.length; i++) {
                System.out.print("monthod " + traceElements[i].getMethodName());
                System.out.println("(" + traceElements[i].getClassName());
                System.out.println(traceElements[i].getLineNumber() + ")");
            }
        }
    }
    
    private static int sum(int[] list) {
        int sum = 0;
        for(int i = 0; i <= list.length; i++) {
            sum += list[i];
        }
        return sum;
    }
}

finally语句

无论异常是否出现,都希望执行某些代码,这时可以采取finally子句:

public class test {
    public static void main(String[] args) {
        PrintWriter output = null;
        try {
            output = new PrintWriter("wu.txt");
            output.println("wlecome tio java");
        } catch(IOException ex) {
            ex.printStackTrace();
        } finally {
            if(output != null)
                output.close();
        }
        System.out.println("End of the program");
    }
}

版权声明:本文内容由阿里云实名注册用户自发贡献,版权归原作者所有,阿里云开发者社区不拥有其著作权,亦不承担相应法律责任。具体规则请查看《阿里云开发者社区用户服务协议》和《阿里云开发者社区知识产权保护指引》。如果您发现本社区中有涉嫌抄袭的内容,填写侵权投诉表单进行举报,一经查实,本社区将立刻删除涉嫌侵权内容。

分享:
开发与运维
使用钉钉扫一扫加入圈子
+ 订阅

集结各类场景实战经验,助你开发运维畅行无忧

其他文章