2010-06-21 238 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

相關問題