java异常处理机制示例(java抛出异常、捕获、断言)
作者:
这是一个介绍基本异常处理的小例子,包括抛出,捕获,断言,日志。
Java异常处理通过5个关键字try、catch、throw、throws、finally进行管理。基本过程是用try语句块包住要监视的语句,如果在try语句块内出现异常,则异常会被抛出,你的代码在catch语句块中可以捕获到这个异常并做处理;还有以部分系统生成的异常在Java运行时自动抛出。你也可以通过throws关键字在方法上声明该方法要抛出异常,然后在方法内部通过throw抛出异常对象。
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("最后他们过上了幸福的生活!!!!(完)");
  }
 }
}
