如何将exception写入文本文件
import java.io.*; class FileWrite { public static void main(String args[]) { try{ // Create file FileWriter fstream = new FileWriter("out.txt"); BufferedWriter out = new BufferedWriter(fstream); out.write("Hello Java"); //Close the output stream out.close(); }catch (Exception e){//Catch exception if any // CAN I WRITE THE EXCEPTION TO THE TEXT FILE } } }
我正在写文件到文件。 我可以将catch
块中抛出的exception写入out.txt
文件吗?
您不应该也可能无法将该exception写入该文件,该文件可能导致该错误。 但您可以尝试使用log4j,如已建议的log4j和catch块。 你可以简单地添加一些东西:
private static final Category log = Category.getInstance(MyClass.class.getName()); ... catch (Exception e) { logger.log(e.getMessage()); }
详细了解此处或此post中的日志记录。 另请查看log4j文档 。
是的,您可以将exception写入文本文件。 但是,如果exception发生在您创建FileWriter或BufferedWriter的行中,那么您将无法根据这些对象的状态使用此对象。 您还需要在try块之外声明这些对象的实例以启用可见性。
您不能使用try
块中的相同out
变量来写入out.txt
,因为exception可能已经在try
块中的任何位置抛出。 这意味着在catch
块out
可能没有初始化,或者尝试使用它写入将导致您当前捕获的相同exception。
您可以尝试在catch
块中再次打开该文件以编写exception,但由于打开和写入同一文件失败,因此不太可能。
在catch
块中调用以下方法并传递该对象。 这将做你的工作:
public static void writeException(Exception e) { try { FileWriter fs = new FileWriter("out.txt", true); BufferedWriter out = new BufferedWriter(fs); PrintWriter pw = new PrintWriter(out, true); e.printStackTrace(pw); } catch (Exception ie) { throw new RuntimeException("Could not write Exception to file", ie); } }
作为Ex。
try{ new NullPointerException(); } catch(Exception e){ writeException(e); }
//breaking code } catch (Exception e) { File f = new File("/tmp/someFileYouCanActuallyWriteOn.txt"); if (!f.exists()) f.createNewFile(); e.printStackTrace(new PrintStream(f)); }
但请考虑zachary-yates的评论。 此外,不鼓励捕捉’exception’而不是特定类型 – 但如果你真的想抓住一切,抓住Throwabble