tags:

views:

41

answers:

1

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

+2  A: 

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..

Jack
That was just what I needed, thanks.
deuseldorf
An alternative to this, is an initialization block. Just another `{` and `}` surrounding the `try-catch` block.
BalusC