Holtorf
Holtorf

Reputation: 1491

What causes a 'Type expected' error in JSP?

In a JSP file I'm getting a:

Type expected (found 'try' instead)

Error while attempting to set up a connection. This leaves me with two questions. What is going wrong here? and more generally, what causes 'Type Expected' Errors in JSP? Since I can't find an explanation of the error in a Google search. Here's the code.

<%!
class ThisPage extends ModernPage
{
     try{
        Connection con=null;
        PreparedStatement pstmt=null;
        con = HomeInterfaceHelper.getInstance().getConnection();
        pstmt = con.prepareStatement("sql goes here");
        ResultSet rs = pstmt.executeQuery();
        con.close();  
    }
    catch (Exception e){
        System.out.println("sql error: exception thrown");
    }
}
%>

Edited to show more code

Upvotes: 0

Views: 320

Answers (1)

Jack
Jack

Reputation: 133629

Usually you can't add a try .. catch block inside a class declaration, you should at least put it inside a method like the constructor of the class or a static { } block.

I don't know if JSP's syntax is different but did you try something like:

class ThisPage extends ModernPage {
  Connection con;
  PreparedStatement pstmt;


  ThisPage() {
    try{
      con=null;
      pstmt=null;
      con = HomeInterfaceHelper.getInstance().getConnection();
      pstmt = con.prepareStatement("sql goes here");
      ResultSet rs = pstmt.executeQuery();
      con.close();  
    }
    catch (Exception e){
        System.out.println("sql error: exception thrown");
    }
  }
}

If you look at Java Language Specification you can see that a TryStatement cannot be inserted inside a class declaration..

Upvotes: 2

Related Questions