2010-06-21 234 views
0

在JSP文件中,我得到:是什么原因导致JSP中出现'Type expected'错误?

Type expected (found 'try' instead) 

尝试建立连接时出错。这让我有两个问题。这里出了什么问题?更一般地说,是什么导致JSP中的“预期类型”错误?由于我无法在Google搜索中找到错误的解释。这是代码。

<%! 
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"); 
    } 
} 
%> 

编辑以显示更多代码

+3

听起来像你在某处有语法错误;你能在'try'之前粘贴几行吗? – ZoogieZork 2010-06-21 20:42:44

+0

听起来像一个失踪';'在我尝试之前... – Tommy 2010-06-21 20:50:42

+0

感谢您的建议Zoogie。但除此之外,这是整个文件。这可能是问题吗? – Holtorf 2010-06-21 21:02:29

回答

2

通常你不能添加一个类声明内try .. catch块,你至少应该把它像类的构造函数或static { }块的方法中。

我不知道JSP语法不同,但没有你尝试类似:

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"); 
    } 
    } 
} 

如果你看看Java Language Specification你可以看到一个TryStatement不能在一个类声明中插入..

+0

这正是我所需要的,谢谢。 – Holtorf 2010-06-21 21:24:34

+0

另一种方法是初始化块。围绕'try-catch'块的另一个''和'}' – BalusC 2010-06-21 21:48:59

相关问题