/*
需求:在实际开发过程中,对出现的异常,我们通常是建立一个日志文件来存储异常信息的
      包括异常发生的时间好异常的内容,是编写类似的异常日志信息程序
思路:1 整体的思路就是要将信息输出到一个文件中,这涉及到IO操作
  2 日期时间的格式化操作
      3 异常的处理代码
      只要将这三个整合就可以实现需求了   
  
步骤:1 定义异常捕获和处理代码在catch代码块;
  2 在catch代码块中加入文件输出流操作,
  3 要写入到文件中的内容包括日期时间,当然写入的是定义好的格式
    还有异常的具体信息

*/
package exceptionjournal;
import java.io.*;
import java.util.*;
import java.text.*;
class MathException  extends Exception
{
String message;
MathException(String message)
{
super(message);
}
}
class ExceptionJournal
{
public static void main(String []args)
{
try
{
int b=div(6,0);
}
catch(MathException me)
{
Date d=new Date();
SimpleDateFormat sdf=new SimpleDateFormat("yyyy年mm月dd日 HH时mm分ss妙");
String time=sdf.format(d);
PrintStream ps=null;
try
{
ps=new PrintStream("exceptioninformation.txt");
ps.println(time);
ps.println(me.toString());
ps.flush();
}
catch(IOException open)
{
throw new RuntimeException("异常日志文件打开异常");
}
finally
{
try
{
if(ps!=null)
ps.close();
}
catch(IOException close)//为什么这里不可以抛出IOException呢?错误提示为
//在相应的 try 语句主体中不能抛出异常错误IOException
                                     //可是如果把IOException换成Exception就可以了,这是为何啊?

{
throw new RuntimeException("异常日志文件关闭异常");
}
}

}
finally
{
System.out.println("over ");
}

}
public static int div(int a,int b) throws MathException
{
if(0==b)
throw new MathException("除数为0了");
return a/b;
}
}问题在catch语句块

解决方案 »

  1.   

    你笔误吗?
    //可是如果把IOException换成Exception就可以了,这是为何啊? 其实想问?
    //如果把IOException换成RuntimeException就可以了,这是为何啊?运行时异常与编译时异常是有很大概率要被问到的,这些属于基本概念。
    1.RuntimeException,也就是运行时异常,表示你的代码本身存在BUG,比如你提到的ArrayIndexOutOfBoundsException,数组下标越界,这个属于代码有问题,数组定义的长度不够实际使用,不处理肯定会报错,如果你操作某个模块发现能正常运行,那只是因为代码还没跑到这个错误的地方而已。。控制台一旦报RuntimeException,就必须要处理。。没有例外的。而且,处理RuntimeException,不是try-catch能解决的。。try-catch在这里使用毫无意义。2.不是RuntimeException,就是编译时异常,异常只有这两种了。比如你在处理文件流时的I/O问题(IOException),就属于编译时异常。这个时候用thr{}catch 来捕获或者 throws即可。
      

  2.   


    因为,ps.close(); 不会抛出异常。 所以你不能catch IOException(因为IOException不RuntimeException)。
    什么是RuntimeException看我前面楼说的。而Exception是所有Exception的父类,包括RuntimeException。 所以可以catch。关键还是楼主没有搞清楚,运行时异常与编译时异常。
      

  3.   

    /**
         * Closes the stream.  This is done by flushing the stream and then closing
         * the underlying output stream.
         *
         * @see        java.io.OutputStream#close()
         */
        public void close() {
    synchronized (this) {
        if (! closing) {
    closing = true;
    try {
        textOut.close();
        out.close();
    }
    catch (IOException x) {
        trouble = true;
    }
    textOut = null;
    charOut = null;
    out = null;
        }
    }
        }ps.close()源码没有抛出异常,难怪
      

  4.   

    是因为PrintStream的close不会抛异常,之前写的都是BufferedWriter,而它的close会抛异常
      

  5.   

    for(int i=0;i<x;i++)
    {
       copy();
       paste();
    }
      

  6.   

    怎么贴那种 在java code框 里的代码