异常类面试题

一:读程序写结果

 1 /*
 2  * 异常三步走:try检测异常,catch捕获异常,finally关闭资源.
 3  */
 4 public class Test {
 5     public static void main(String[] args) {
 6         Demo demo=new Demo();
 7         int x=demo.method();
 8         System.out.println(x);
 9     }
10 
11 }
12 
13 class Demo {
14     public int method() {
15         int x = 10;
16         try {
17             x = 20;
18             System.out.println(x / 0);//出现异常
19             return x;
20         } catch (ArithmeticException e) {//捕获异常,给x重新赋值并对x建立返回路径(并没有返回x),再去检查看有没有finally代码块
21             x = 30;
22             return x;
23         } finally {//重新给x赋值40(但是catch中建立返回路径中的x仍为30),返回路径中的x值
24             x = 40;//finally中不要写return语句(可以写),但是try和catch中的赋值语句就没有意义了.
25         }
26     }
27 }

二:根据题意写出相应代码

 1 import java.math.BigDecimal;
 2 import java.math.BigInteger;
 3 import java.util.Scanner;
 4 
 5 /*
 6    键盘录入一个int类型的整数,对其求二进制表现形式
 7      * 如果录入的整数过大,给予提示,录入的整数过大请重新录入一个整数BigInteger
 8      * 如果录入的是小数,给予提示,录入的是小数,请重新录入一个整数
 9      * 如果录入的是其他字符,给予提示,录入的是非法字符,请重新录入一个整数
10  */
11 public class PraticeTest {
12     public static void main(String[] args) {
13         @SuppressWarnings("resource")
14         Scanner sc = new Scanner(System.in);
15         int num = 0;
16         System.out.println("请输入一个整数:");
17         while (true) {
18             String str = sc.next();
19             try {
20                 num = Integer.parseInt(str);// 输入不是符合要求整数,抛出异常
21                 System.out.println(num + "转换成二进制为:" + Integer.toBinaryString(num));
22                 break;
23             } catch (Exception e) {
24                 try {
25                     new BigInteger(str);// 若不是过大整数,抛出异常
26                     System.out.println("您输入的是一个过大整数,请重新输入一个整数:");
27                 } catch (Exception e1) {
28                     try {
29                         new BigDecimal(str);// 若不是小数,抛出异常
30                         System.out.println("您输入的是一个小数,请重新输入一个整数:");
31                     } catch (Exception e2) {
32                         System.out.println("您输入的是非法字符,请重新输入一个整数:");
33                     }
34 
35                 }
36 
37             }
38         }
39 
40     }
41 
42 }
原文地址:https://www.cnblogs.com/le-ping/p/7469003.html