一:异常
所有的异常都是由Throwable继承而来,在下一层立即分解为:Error和Exception。
Error类层次结构描述了java运行时系统的内部错误和资源耗尽错误。应用程序不应抛出这种类型的对象,如果出现了这种错误,除了通知用户无能为力。所以不做过多关注
Exception层次分为两个分支:一个分支派生于RuntimeException(可避免发生),另一个包含其他异常。划分两个分支的规则是:由程序错误导致的异常属于RuntimeException;而程序本身没有问题,类似像IO这种错误就是其他异常
RuntimeException和Error属于非受查异常,禁止用throws子句声明(告诉JVM可能发生什么异常)。其他异常属于可受查异常,可以声明。Error无法控制,Exception应该避免发生,所以对于这这两者声明毫无意义。对于Exception来说应该用try catch子句有效处理,而不是声明它发生的可能性。
二:断言
package asserttest;
public class assertTest {
public static void main(String[] args) {
// TODO Auto-generated method stub
ClassLoader.getSystemClassLoader().setDefaultAssertionStatus(true);
int x = -10;
assert x>0:"断言失败";
System.out.println(x);
}
}
断言失败则输出冒号之后的表达式:“断言失败”
三:日志
package log;
import java.io.IOException;
import java.util.logging.FileHandler;
import java.util.logging.Level;
import java.util.logging.LogRecord;
import java.util.logging.Logger;
import java.util.logging.SimpleFormatter;
/**
* @author Administrator
* 将日志记录写入到文件中
*
*/
class TestLoggingToFile {
public static void main(String[] args) throws SecurityException, IOException {
//日志记录器
Logger logger = Logger.getLogger("chapter07");
//日志处理器
FileHandler fileHandler = new FileHandler("d:\\test.txt");
//需要记录的日志消息
LogRecord lr = new LogRecord(Level.FINE, "This is a text log.");
logger.setLevel(Level.ALL);
//为处理器设置日志格式:Formatter
SimpleFormatter sf = new SimpleFormatter();
fileHandler.setFormatter(sf);
//注册处理器
logger.addHandler(fileHandler);
//记录日志消息
logger.log(lr);
logger.warning("我是warning级别的警告");
}
}