Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

void cannot be dereferenced

Tags:

java

I have a method of editing members, and I want to print out errors into a file, but I keep getting the void cannot be dereferenced error if I try to print out the stack trace into a Error_Report.txt file. Is there anyway I can print it out? This is my code.

public void edit() {
  FileWriter fw = new FileWriter(new File("Error_Report.txt"));
  Connection con;
  Statement stmt;
  ResultSet rs;

  int id = (int)_id.getSelectedItem();
  String name = _name.getText();
  String user = _username.getText();
  String pass = _password.getText();
  String pos = _position.getSelectedItem().toString();

  try {
    Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
    con = DriverManager.getConnection("jdbc:odbc:collegesys", 
                                      "root", "0blivi0n");

    stmt = con.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE,
                               ResultSet.CONCUR_READ_ONLY);

    PreparedStatement prep = con.prepareStatement("UPDATE `main` WHERE ID = ?");
    prep.setInt(1, id);
    prep.setString(2, name);
    prep.setString(3, user);
    prep.setString(4, pass);
    prep.setString(5, pos);

    prep.execute();
  } catch(SQLException sqle) {
    String sql = sqle.printStackTrace().toString();
    fw.write("" + sql);
  } catch(ClassNotFoundException cnfe) {
    fw.write("" + cnfe);
  }
}
like image 341
Nathan Kreider Avatar asked Aug 09 '26 05:08

Nathan Kreider


2 Answers

Your problem is that printStackTrace doesn't return anything, so there's nothing to convert to a string. Write it like this.

PrintWriter writer = new PrintWriter(fw);
sqle.printStackTrace(writer);
writer.close();
like image 71
Dawood ibn Kareem Avatar answered Aug 11 '26 20:08

Dawood ibn Kareem


sqle.printStackTrace() returns a void and can't be used as parameter. Change your code to something like this:

catch(SQLException sqle) {
    StringBuilder sb = new StringBuilder();
    StackTraceElement[] st = sqle.getStackTrace();
    for(StackTraceElement s : st) {
        sb.append(s);
        sb.append('\n');
    }
    fw.write(sb.toString());
} 
like image 42
Luiggi Mendoza Avatar answered Aug 11 '26 20:08

Luiggi Mendoza