Menangkap pengecualian yang muncul dalam program dapat digunakan untuk pemeliharaan nanti! Lakukan tes sederhana!
Salinan kode adalah sebagai berikut:
Paket HelpEntity;
impor java.io.bufferedReader;
impor java.io.file;
impor java.io.filereader;
impor java.io.filewriter;
impor java.io.printwriter;
impor java.text.simpledateFormat;
impor java.util.date;
log kelas publik {
file file pribadi = null;
File publik getFile () {
pengembalian file;
}
public void setFile (file file) {
this.file = file;
}
public void savelog (Exception E, String Youname) {
mencoba {
String nowpath = null;
nowpath = system.getProperty ("user.dir");
String Temppath = null;
this.file = file baru (nowpath);
Temppath = this.file.getParent ();
if (Temppath == null) {
this.file = file baru (nowpath);
}
this.file = File baru (Temppath + "" + File.Separator + "log.txt");
Printwriter writer = null;
FileWriter FileWrite = FileWriter baru (file, true);
penulis = printwriter baru (FileWrite);
writer.Append (System.getProperty ("Line.Separator")
+ new SimpleDateFormat ("yyyy-mm-dd: hh: mm: ss")
.format (tanggal baru ()) + "__" + youname);
writer.append (System.getProperty ("Line.Separator"));
writer. lampin ("**************************" + e.tostring ()
+ "*********************************");
writer.append (System.getProperty ("Line.Separator"));
E.PrintStackTrace (penulis);
writer.flush ();
writer.close ();
} catch (Exception e2) {
e2.printstacktrace ();
}
}
}