对Try-Catch的理解

这是自定义的DrunkException类:

public class DrunkException extends Exception{
    public DrunkException(){}
    public DrunkException(String message){
    	super(message);
    }
    
}


这是一个抛出异常链,只要产生异常就可以抛出给调用者处理,并且可以在catch中继续向上抛。

public class ChainTest {

	public static void main(String[] args) {
		// TODO Auto-generated method stub
		ChainTest ct = new ChainTest();
		try{
			ct.Test3();
		}catch(Exception e){
			e.printStackTrace();
		}
	}
	public void Test3() throws Exception{
		try{
    		Test2();
    	}catch(Exception e){
    		//Exception run=new Exception(e);
    		//throw run;
    		throw e;
    	}
	}
    public void Test2() throws Exception{
    	try{
    		Test1();
    	}catch(DrunkException e){
    		//Exception run=new Exception(e);
    		//throw run;
    		//DrunkException drunkEx = new DrunkException(e.toString());
    		//throw drunkEx;
    		throw e;
    	}
    }
    public void Test1() throws DrunkException{
    	throw new DrunkException("执行了DrunkException");
    }
}


关于finally需要说的就是,无论执不执行catch,finally是一定会执行的。

一些Exception的类型可以在网上自行查阅

猜你喜欢

转载自blog.csdn.net/shl_shl/article/details/66975589