2014-01-28 69 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不必在那里处理它。 (对于任何“真正的”应用程序,当然,你应该捕捉异常,并提出一个很好的格式化的错误信息。)

(你可以感谢古迪纳夫先生为这一切混乱的。)

相关问题