异常捕获举例之输入非数字异常

import java.io.*;
public class exceptionTester {
     public static void main(String args[])
    {
        System.out.println("please enter the number1");
        int number1 = Keyboard.getInteger();
        System.out.println("please enter the number2");
        int number2 = Keyboard.getInteger();
        int number3 = number1/number2;
        System.out.println(number3);
    }
}

//exceptionTester类位主测试类

import java.io.*;
public class Keyboard {
    static BufferedReader inputStream = new BufferedReader(new InputStreamReader(System.in));
    public static int getInteger(){
        try{
            return (Integer.valueOf(inputStream.readLine().trim()).intValue());
        } catch (Exception e) {
            e.printStackTrace();
            return 0;
        }
    }
    public static String getString(){
        try {
            return(inputStream.readLine());
        } catch(IOException e){
            return "0";
        }
    }
}

//Keyborad类在getInteger()方法里将会捕捉产生的任何异常并输出异常为了处理输入的字母而非数字可以使用Keyboard.getString()取得字符后转换

//当我们输入的不是数字时编译器就会产生以下错误

java.lang.NumberFormatException: For input string: "a"
    at java.lang.NumberFormatException.forInputString(NumberFormatException.java:65)
    at java.lang.Integer.parseInt(Integer.java:580)
    at java.lang.Integer.valueOf(Integer.java:766)
    at Keyboard.getInteger(Keyboard.java:6)
    at exceptionTester.main(exceptionTester.java:8)
Exception in thread "main" java.lang.ArithmeticException: / by zero
    at exceptionTester.main(exceptionTester.java:9)

 

你可能感兴趣的:(笔记)