java异常常见问题汇总

package shilian.mylean.exception;  
import org.testng.annotations.Test;  
  
public class TestException {  
  
    /**  
     * IOException是编译期异常,这里编译时会报错  
     */  
    @Test  
    public void test1() {  
        try{  
            start();  
            // }catch(IOException ioe){  
        } catch(Exception ioe) {  
            ioe.printStackTrace();  
        }  
    }  
  
    public static void start() {  
        System.out.println("Java Exception interivew question Answers for Programmers");  
    }  
  
    /**  
     * 第一个catch将异常处理过之后,下面将不会执行  
     */  
    @Test  
    public void test4() {  
        try{  
            start1();  
        } catch(Exception ex) {  
            ex.printStackTrace();  
        }  
/*        catch (RuntimeException re) {  
            re.printStackTrace();  
        }*/  
    }  
  
    public static void start1() throws RuntimeException {  
  
        throw new RuntimeException("Not able to Start");  
    }  
  
  
    /**  
     * 程序返回1,程序先运行return,再运行finally语句  
     */  
    @Test  
    public void test2() {  
        System.out.println(test());  
    }  
  
    static int test() {  
        int x = 1;  
        try{  
            return x;  
        } finally {  
            ++x;  
        }  
    }  
  
    /**  
     * 程序打印2  
     */  
    @Test  
    public void test3() {  
  
        System.out.println(get());  
    }  
  
    public static int get() {  
        try{  
            return 1;  
        } finally {  
            return 2;  
        }  
    }  
  
    /**  
     * finally中的代码比return语句后执行  
     */  
    @Test  
    public void test6() {  
        System.out.println(new TestException().start6());  
    }  
  
    int start6() {  
        try{  
            return func1();  
        } finally {  
            return func2();  
        }  
    }  
  
    int func1() {  
        System.out.println("func1");  
        return 1;  
    }  
  
    int func2() {  
        System.out.println("func2");  
        return 2;  
    }  
  
  
    /**  
     * 如果执行finally代码块之前JVM退出了,finally块中的代码还会执行吗?  
     */  
    @Test  
    public void test7() {  
        System.out.println(new TestException().start7());  
    }  
  
    static int start7() {  
        try{  
            System.out.println("try");  
            System.exit(0);  
        } finally {  
            return 1;  
        }  
    }  
  
    /**  
     * 空指针异常  
     */  
    @Test  
    public void test8() {  
        System.out.println(start8(null));  
    }  
  
    static String start8(String name) {  
  
        if("shilian".equals(name)) {  
            return "hello world" + name;  
        }  
  
        return null;  
    }  
}  

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值