2014-01-28 67 views
0

我是新來的JAVA剛學過它的基礎知識,現在我想學習一些先進的JAVA我不知道它的前進與否,但我想要做什麼是當我點擊搜索按鈕,我會送1個HTTP調用,當我刪除HTTP請求的代碼或當我刪除搜索按鈕的代碼那麼它單獨卻不能在一起不可編譯的源代碼 - 未報告的異常java.lang.Exception;必須被捕獲或聲明爲拋出

在這裏工作是我的代碼:

/* 
* To change this license header, choose License Headers in Project Properties. 
* To change this template file, choose Tools | Templates 
* and open the template in the editor. 
*/ 

package google; 
import java.io.*; 
import java.net.*; 
import java.awt.event.*; 
import javax.swing.*; 
/** 
* 
* @author user 
*/ 

public class Google extends JFrame { 

    private final String USER_AGENT = "Mozilla/5.0"; 

    public Google() { 
     initUI(); 
    } 

    private void callUrl() throws Exception { 

     String url = "http://www.google.com/search?q=mkyong"; 

     URL obj = new URL(url); 
     HttpURLConnection con = (HttpURLConnection) obj.openConnection(); 

     // optional default is GET 
     con.setRequestMethod("GET"); 

     //add request header 
     con.setRequestProperty("User-Agent", USER_AGENT); 

     int responseCode = con.getResponseCode(); 
     System.out.println("\nSending 'GET' request to URL : " + url); 
     System.out.println("Response Code : " + responseCode); 

     BufferedReader in = new BufferedReader(
       new InputStreamReader(con.getInputStream())); 
     String inputLine; 
     StringBuffer response = new StringBuffer(); 

     while ((inputLine = in.readLine()) != null) { 
      response.append(inputLine); 
     } 
     in.close(); 

     //print result 
     System.out.println(response.toString()); 

    } 

    private void initUI() { 

     JPanel panel = new JPanel(); 
     getContentPane().add(panel); 

     panel.setLayout(null); 

     JButton searchButton = new JButton("Search"); 
     searchButton.setBounds(50, 60, 80, 30); 

     searchButton.addActionListener(new ActionListener() { 
      @Override 
      public void actionPerformed(ActionEvent event) { 
       callUrl(); 
      } 
     }); 

     panel.add(searchButton); 

     setTitle("Search"); 
     setSize(300, 200); 
     setLocationRelativeTo(null); 
     setDefaultCloseOperation(EXIT_ON_CLOSE); 
    } 

    public static void main(String[] args) throws Exception { 
     SwingUtilities.invokeLater(new Runnable() { 
      @Override 
      public void run() { 
       Google ex = new Google(); 
       ex.setVisible(true); 
      } 
     }); 
    } 

} 

對不起,如果這個問題已經存在,我搜索了很多,但沒有得到正確的解決方案。 感謝

錯誤:

Exception in thread "AWT-EventQueue-0" java.lang.RuntimeException: Uncompilable source code - unreported exception java.lang.Exception; must be caught or declared to be thrown 
    at google.Google$1.actionPerformed(Google.java:70) 
    at javax.swing.AbstractButton.fireActionPerformed(AbstractButton.java:2018) 
    at javax.swing.AbstractButton$Handler.actionPerformed(AbstractButton.java:2341) 
    at javax.swing.DefaultButtonModel.fireActionPerformed(DefaultButtonModel.java:402) 
    at javax.swing.DefaultButtonModel.setPressed(DefaultButtonModel.java:259) 
    at javax.swing.plaf.basic.BasicButtonListener.mouseReleased(BasicButtonListener.java:252) 
    at java.awt.Component.processMouseEvent(Component.java:6505) 
    at javax.swing.JComponent.processMouseEvent(JComponent.java:3320) 
    at java.awt.Component.processEvent(Component.java:6270) 
    at java.awt.Container.processEvent(Container.java:2229) 
    at java.awt.Component.dispatchEventImpl(Component.java:4861) 
    at java.awt.Container.dispatchEventImpl(Container.java:2287) 
    at java.awt.Component.dispatchEvent(Component.java:4687) 
    at java.awt.LightweightDispatcher.retargetMouseEvent(Container.java:4832) 
    at java.awt.LightweightDispatcher.processMouseEvent(Container.java:4492) 
    at java.awt.LightweightDispatcher.dispatchEvent(Container.java:4422) 
    at java.awt.Container.dispatchEventImpl(Container.java:2273) 
    at java.awt.Window.dispatchEventImpl(Window.java:2719) 
    at java.awt.Component.dispatchEvent(Component.java:4687) 
    at java.awt.EventQueue.dispatchEventImpl(EventQueue.java:735) 
    at java.awt.EventQueue.access$200(EventQueue.java:103) 
    at java.awt.EventQueue$3.run(EventQueue.java:694) 
    at java.awt.EventQueue$3.run(EventQueue.java:692) 
    at java.security.AccessController.doPrivileged(Native Method) 
    at java.security.ProtectionDomain$1.doIntersectionPrivilege(ProtectionDomain.java:76) 
    at java.security.ProtectionDomain$1.doIntersectionPrivilege(ProtectionDomain.java:87) 
    at java.awt.EventQueue$4.run(EventQueue.java:708) 
    at java.awt.EventQueue$4.run(EventQueue.java:706) 
    at java.security.AccessController.doPrivileged(Native Method) 
    at java.security.ProtectionDomain$1.doIntersectionPrivilege(ProtectionDomain.java:76) 
    at java.awt.EventQueue.dispatchEvent(EventQueue.java:705) 
    at java.awt.EventDispatchThread.pumpOneEventForFilters(EventDispatchThread.java:242) 
    at java.awt.EventDispatchThread.pumpEventsForFilter(EventDispatchThread.java:161) 
    at java.awt.EventDispatchThread.pumpEventsForHierarchy(EventDispatchThread.java:150) 
    at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:146) 
    at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:138) 
    at java.awt.EventDispatchThread.run(EventDispatchThread.java:91) 
+0

HTTP:/ /docs.oracle.com/javase/tutorial/essential/exceptions/ – Radiodef

+0

你在哪裏捕捉異常? – Prince

+0

你能給出確切的編譯器錯誤嗎? – Vaandu

回答

1

我剪切和粘貼代碼到Eclipse,它讓我(通過突出顯示錯誤)把一試圍繞以下:

searchButton.addActionListener(new ActionListener() {  
public void actionPerformed(ActionEvent event) { 
      try { 
      callUrl(); 
     } catch (Exception e) { 
      // TODO Auto-generated catch block 
      e.printStackTrace(); 
     } 
     } 
    }); 
+0

這是捕捉調用方法的方式。 – Vaandu

+0

感謝工作接受你的答案,再次感謝:) –

+1

除了,希望這不是如何OP處理異常... –

1

下面的鏈接說,OpenConnection方法可以拋出異常。

如果您使用此方法,則必須使用catch或throw it again。

http://docs.oracle.com/javase/1.5.0/docs/api/java/net/URL.html#openConnection%28%29

編輯:不是引發異常,嘗試這樣

private void callUrl() { 
     try { 
      // your stuff 
     } catch (Exception e) { 
      // print it for sure 
     } 
    } 
+0

如何再次抓取或丟棄它? –

+0

@MohitBumb http://docs.oracle.com/javase/tutorial/essential/exceptions/catch.html – Radiodef

+0

用'callUrl'方法捕捉它。請檢查我的編輯。 – Vaandu

1

HttpURLConnection#openConnection引發一個異常,該callUrl()聲明。 initUI()調用callUrl(),但不聲明異常。這可能幫助:

private void initUI() throws Exception { 

另外,還可以圍繞HttpURLConnection的#的openConnection()用try/catch塊呼籲:

private void callUrl() throws Exception { 

    String url = "http://www.google.com/search?q=mkyong"; 

    URL obj = new URL(url); 
    HttpURLConnection conn; 
    try { 
     conn = (HttpURLConnection) url.openConnection(); 
    } catch (IOException e) { 
     e.printStackTrace(); 
     // handle the failed connection cleanly... 
    } 
    // and then continue processing 
2

這還不是很具體的,以你的問題,但它會幫助你瞭解java中的異常處理。

有兩種例外

  • 經過異常
  • 未檢查異常

經過異常應該在代碼來處理,這意味着你要麼需要在方法或拋出與處理例外,以便該方法的調用者會照顧。

要發現異常,您需要使用trycatch。如果你不想處理異常,你可以聲明你的方法爲throws SomeException,以便調用者處理。

例如:

public String getContentsOfFile(String filePath) { 
    try { 
     File file = new File(filePath); 
     FileInputStream fis = new FileInputStream(file); 
     String contents = //convert stream to string and return 
     return contents; 
    } catch(FileNotFoundException e){ 
     //Here this method is interested in handling the checked exception. 
    } 
    return null; 
} 

如果你不想處理異常(你讓你的方法拋出異常)

public String getContentsOfFile(String filePath) throws FileNotFoundException { 

    File file = new File(filePath); 
    FileInputStream fis = new FileInputStream(file); 
    String contents = //convert stream to string and return 
    return contents;   
} 

另一個最佳實踐是,你能趕上檢查異常並拋出Unchecked異常(RuntimeException),以便該方法的調用者不需要處理該異常。 Spring廣泛使用這種方法。

try { 
..... 
} catch (FileNotFoundException fne) { 
    //log fne 
    throw new RuntimeException(fne); 
} 

這裏是什麼時候,當選擇非受檢異常選擇經過異常和問題。 When to choose checked and unchecked exceptions

1

由於您是Java新手,我建議您使用Eclipse(IDE)編輯代碼。它會自動爲你提出建議。

在搜索按鈕的ActionListener 「的actionPerformed」 通話,則需要進行如下修改代碼:

searchButton.addActionListener(new ActionListener() { 
    @Override 
    public void actionPerformed(ActionEvent event) { 
     try { 
     callUrl(); 
    } catch (Exception e) { 
     // TODO Auto-generated catch block 
     e.printStackTrace(); 
    } 
    } 

});

我所做的只是添加一個try/catch處理函數,因爲你已經聲明瞭「callUrl()」函數拋出異常。我使用粘貼的代碼運行上面的代碼 - 這是有效的。

讓我知道如果你需要進一步的幫助。

0

這是你的錯誤:

private void callUrl() throws Exception { 

當你說一個方法拋出Exception那麼每個調用者必須以某種方式處理該異常。幾乎沒有必要說一種方法拋出Exception(它是所有「檢查」異常的母親)與一些更精確的條件,特別是如果該方法只拋出「未檢查」的異常(Error的子類或RuntimeException),那麼根本就不需要使用throws子句。

在你似乎有一些IOException異常的可能性,這意味着你將需要捕捉或者宣佈上述情況,但應該足以說throws IOException VS throws Exception,或者,可能會更好,catch IOException異常的方法內部和處理它。 (它總是最好地處理接近拋之儘可能的情況下的例外)。

提示:對於一個測試用例或「快速和骯髒的」程序它足以說throws WhateverExceptionmain方法,VS不必在那裏處理它。 (對於任何「真正的」應用程序,當然,你應該捕捉異常,並提出一個很好的格式化的錯誤信息。)

(你可以感謝古迪納夫先生爲這一切混亂的。)

相關問題