java面试exception相关

面试题目一:

代码如下,问下面程序执行完毕后结果是什么?

public class ExceptionTest{

    public static void main(String[] args) {
        try {
            String s = null;
            return;
        } catch(Exception e){
            System.out.println("exception");
        } finally {
            System.out.println("finally");
        }
    }
}

答案:结果是输出finally,当try块执行到return的时候并不会立刻return而是会转向到finally块,等finally块执行完毕之后在进行return。

面试题目二:

代码如下,问下面的程序执行完毕后结果是什么?

public class ExceptionTest{

    public static int output() {
        try {
            String s = null;
            return 2;
        } catch(Exception e){
            System.out.println("exception");
        } finally {
            System.out.println("finally");
            return 4;
        }
        
    }

    public static void main(String[] args) {
        int result = output();
        System.out.println(result);
    }
}

答案:执行结果是输出finally和4,当try块执行到return语句的时候会转向执行finally块,当finally块中也有return语句的时候就会以该return为最终的return。(猜测,具体也不知道原理)

面试题目三:

代码如下,问下面的程序执行完毕后结果是什么?

public class ExceptionTest{

    public static int output() {
        try {
            String s = null;
            System.exit(0);
        } catch(Exception e){
            System.out.println("exception");
        } finally {
            System.out.println("finally");
            return 4;
        }
        
    }

    public static void main(String[] args) {
        int result = output();
        System.out.println(result);
    }
}

答案:控制台什么都没有输出,因为执行到System.exit(0)的时候就会结束虚拟机了,连程序都退出了,怎么可能还会输出。

笔试题目四:

代码如下,问下面的程序能否编译通过?

public class ExceptionTest {
    
    public void doSomething() throws ArithmeticException {
        System.out.println("do something");
    }
    
    public static void main(String[] args) {
        ExceptionTest test = new ExceptionTest();
        test.doSomething();
    }
}

答案:能够编译通过,因为doSomething方法抛出的是uncheckedException所以在main方法中调用该方法时并不需要对其进行处理。所以对于异常的处理具体还要看调用方法所抛出的异常类型.上述代码如果抛出的是IOException则就需要在main方法中进行try-cath或继续向JVM抛出异常,因为IOException是checkedException.

补充知识点:

  • 处理异常的手段:1.try-catch 2. 继续向上抛出
  • java异常分为checkedException与uncheckedException(也称为runtimeException)
  • java允许我们对于uncheckedException进行try-catch或抛出,也允许我们不对其进行任何处理

笔试题目五:

代码如下,问下面的程序能否编译通过?

import java.io.IOException;
public class ExceptionTest {
    
    public void doSomething() throws IOException {
        System.out.println("do something");
    }
    
    public static void main(String[] args) {
        ExceptionTest test = new ExceptionTest();
        try {
            test.doSomething();
        } catch (Exception e) {
        } catch (IOException e) {
        }
        
    }
}

答案:编译通不过,IOException块无法到达,在try-catch代码块中当有匹配的catch时就会忽略后面所有的catch。所以在上述代码中Exception是所有异常的父类,一定会进入到该catch块,后面的IOException catch块就毫无意义了。在使用try-catch进行异常捕获的时候有一个原则就是:异常范围要从小到大的写

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

友情链接更多精彩内容