异常的探索-Thinking in java

2014-11-24 02:57:47 · 作者: · 浏览: 1

以前对异常一点也不陌生,但是看完Thinking In Java这一张厚才发现,异常其实是非常复杂的玩意,涉及到java内存的堆栈的查找,程序的中断等等,可见一斑,下面贴上代码,好好研究一下异常,可谓是JAVa的精华啊


package com.bird.thinking;

class MyException extends Exception {// 自己写的异常类,有两个构造方法

private static final long serialVersionUID = 1L;

public MyException() {
}

public MyException(String msg) {
super(msg);
}
}

public class FullConstructots {

/**
* @PAT throws是用来声明一个方法可能抛出的所有异常信息 throw则是指抛出的一个具体的异常类型。
* 通常在一个方法(类)的声明处通过throws声明方法(类)可能抛出的异常信息,而在方法(类)内部通过throw声明一个具体的异常信息。
* throws通常不用显示的捕获异常,可由系统自动将所有捕获的异常信息抛给上级方法;
* throw则需要用户自己捕获相关的异常,而后在对其进行相关包装,最后在将包装后的异常信息抛出。
* @param args
* @author bird
*/
public static void f() throws MyException {//调用不带参数的异常构造函数
System.out.println("Throwing MyException from f()");
throw new MyException();
}

public static void g() throws MyException{//调用带参数的异常构造函数
System.out.println("Throws MyEception from g()");
throw new MyException("OH My God in g()");
}

public static void main(String[] args) {
try{
f();
}catch(MyException e){
e.printStackTrace(System.out);
}


try{
g();
}catch(MyException e){
e.printStackTrace(System.out);
}

}

}

输出结果

Throwing MyException from f()
com.bird.thinking.MyException
at com.bird.thinking.FullConstructots.f(FullConstructots.java:27)
at com.bird.thinking.FullConstructots.main(FullConstructots.java:37)
Throws MyEception from g()
com.bird.thinking.MyException: OH My God in g()
at com.bird.thinking.FullConstructots.g(FullConstructots.java:32)
at com.bird.thinking.FullConstructots.main(FullConstructots.java:44)

下面的是将异常记录到日志中的更加正规的方法汇总

package com.bird.thinking;

import java.io.PrintWriter;
import java.io.StringWriter;
import java.util.logging.Logger;


class LoggingExceptions extends Exception{//使用异常记录日志中,更加规范

private static final long serialVersionUID = 1L;
private static Logger logger = Logger.getLogger("LoggingException");
public LoggingExceptions(){
StringWriter trace = new StringWriter();
printStackTrace(new PrintWriter(trace));
logger.severe(trace.toString());
}
}
public class LoggingException {//使用java.util.logging工具将输出记录到日志中

/**
* @param args
* @author bird
*/
public static void main(String[] args) {
try{
throw new LoggingExceptions();
}catch(LoggingExceptions e){
System.err.println("Caughy"+ e);//最好使用错误流去输出异常,这样也是更加规范
}
}

}

输出结果
2011-10-2 21:54:33 com.bird.thinking.LoggingExceptions
严重: com.bird.thinking.LoggingExceptions
at com.bird.thinking.LoggingException.main(LoggingException.java:26)

Caughycom.bird.thinking.LoggingExceptions

看清楚,亲,是红色的哦,亲,不是我自己加的,在Eclipse中运行就是红色,好好看看错误输出流,呵呵。

摘自:blog.csdn.net/a352193394