java入门知识点8:异常

1.异常分类
在这里插入图片描述
2.异常处理

try-catch:
抛出、捕获、处理异常

语法:
try{
//抛出异常
}catch(Exception e(捕获异常)){
//处理该异常
}
多重catch块时需要先遵循子类到父类

try-catch-finally:
finally:必须执行的代码

3.java中异常抛出:无法处理

throw:将产生的异常抛出(动作)
throws:声明要抛出何种类型的异常(声明)
public void 方法名(参数列表)throws 异常列表{
//调用会抛出异常的方法或者:
throw new Exception();
}
自定义异常
class 自定义异常 extends 异常类型{ }

5.java中的异常链

1.test1():抛出“喝大了”异常
2.test2():调用test1(),捕获了“喝大了”异常,并且包装成运行时异常,继续抛出
3.main方法中,调用test2(),尝试捕获test2()方法抛出的异常

public class ChainTest {

	public static void main(String[] args) {
		// TODO Auto-generated method stub
		ChainTest ct = new ChainTest();
		try {
			ct.test2();
		}catch(Exception e) {
			e.printStackTrace();
		}
	}
		
		public void test1() throws DrunkException {
			throw new DrunkException("喝车别开酒");
		}
		
		public void test2()  {
			try{
				test1();
			}catch(DrunkException e) {
				RuntimeException newExc = new RuntimeException("司机一滴酒,亲人两行泪");
				newExc.initCause(e);
				throw newExc;
			}
		}
		
	}

总结:
1>处理运行异常时,采用去合理规避同时辅助try-catch处理
2>在多重catch块后面,可以加一个catch(Exception)来处理可能会被遗漏的异常
3>对于不确定的代码,也可以加上try-catch,处理潜在的异常
4>添加finally语句块去释放占用的资源

猜你喜欢

转载自blog.csdn.net/qq_43501462/article/details/98874997