- package com.hongyuan.test;
- import java.io.IOException;
- import java.util.logging.Level;
- import java.util.logging.Logger;
- public class ExceptionHandleTest {
- static{
- //开启断言,此后由系统类加载器加载的类将启用断言。
- ClassLoader.getSystemClassLoader().setDefaultAssertionStatus(true);
- }
- public static void main(String[] args) {
- /*
- * 抛出,捕获
- */
- try {
- TryCatchTest.run(10, -1);
- } catch (IOException e) {
- e.printStackTrace();
- }
- System.out.println("====================================================");
- //日志
- LogerTest.run();
- System.out.println("====================================================");
- //断言
- AssertTest.div(3,0);
- }
- }
- /*
- * 断言
- */
- class AssertTest {
- public static double div(int b,int a){
- assert a!=0:"你这么用,你小学老师知道吗?";
- return (double)b/a;
- }
- }
- /*
- * 日志
- */
- class LogerTest {
- private static Logger logger=null;
- static{
- //获取日志对象并定义日志级别
- logger=Logger.getLogger(LogerTest.class.getName());
- logger.setLevel(Level.ALL);
- }
- public static void run(){
- //进入方法
- logger.entering(LogerTest.class.getName(), "run");
- //普通信息
- logger.info("又来找我麻烦,这笔账我记下了!!!");
- //警告
- logger.warning("太累了,这活没法干了!!!");
- //严重
- logger.log(Level.SEVERE,"老子不干了!!! ^O^");
- //退出方法
- logger.exiting(LogerTest.class.getName(), "run");
- }
- }
- /*
- * 捕获,抛出
- */
- class TryCatchTest {
- public static void run(int x,int y) throws IOException {
- try{//必须
- if(x<0||y<0){
- throw new IllegalArgumentException("无语了,这让我怎么办啊!!!");
- }
- }catch(Exception e){//可选
- IOException e1=new IOException("你自己看着办吧!");
- e1.initCause(e.getCause());
- throw e1;
- }finally{//可选
- System.out.println("最后他们过上了幸福的生活!!!!(完)");
- }
- }
- }
- //该片段来自于http://www.codesnippet.cn/detail/0307201512999.html
来源: http://www.codesnippet.cn/detail/0307201512999.html