无法编译的源代码——未报告的异常java.lang.Exception;必须被抓住或宣布被扔?

时间:2022-11-29 20:19:08

I'm new in JAVA just learned a basics of it and now I'm trying to learn some advance JAVA I don't know its advance or not but what I'm trying to do is when I click on Search button I'll send 1 http call and when I remove http request code or when I remove search button code then its working individually but not together

我新的JAVA刚学的基本知识,现在我想要学习一些推进JAVA我不知道它的进步,但我想做的就是当我点击搜索按钮发送1 http调用http请求当我删除代码或当我删除搜索按钮代码然后单独工作,但不是在一起

Here's my code :

这是我的代码:

/*
 * 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);
            }
        });
    }

}

Sorry if this question is already exists I searched a lot but didn't get proper solution. Thanks

对不起,如果这个问题已经存在,我搜索了很多,但没有找到合适的解决方案。谢谢

Error :

错误:

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)

6 个解决方案

#1


1  

I cut and pasted your code into Eclipse and it had me (by highlighting an error) put a try around the following:

我将您的代码剪切并粘贴到Eclipse中,它让我(通过高亮显示一个错误)在下面进行了尝试:

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

#2


2  

This is not quite specific to your question, but it will help you in understanding about the exception handling in java.

这并不是针对您的问题,但是它将帮助您理解java中的异常处理。

There are two types of exceptions

有两种类型的异常。

  • Checked exceptions
  • 已检查的异常
  • Unchecked exceptions
  • 未经检查的异常

Checked exceptions should be handled in code, that means you either need to handle with in the method or throw the exceptions so that the caller of the method will take care.

检查异常应该在代码中处理,这意味着您要么需要在方法中处理,要么抛出异常,以便方法的调用者会小心处理。

To catch the exception you need to use try and catch. If you don't want to handle the exception you can declare your method as throws SomeException so that caller would handle.

要捕获异常,您需要使用try和catch。如果您不想处理异常,则可以将方法声明为抛出异常,以便调用方处理。

For Example:

例如:

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

If you don't want to handle the exception (You make your method to throw the exception)

如果您不想处理异常(您使您的方法抛出异常)

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

Another best practice is, you can catch the checked exception and throw a Unchecked exception (RuntimeException) so that the caller of the method doesnt need to handle that. Spring uses this approach widely.

另一个最佳实践是,您可以捕获已检查的异常,并抛出一个未检查的异常(RuntimeException),以便该方法的调用方不需要处理该异常。Spring广泛使用了这种方法。

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

Here is a question on when to choose Checked exceptions and when to choose Unchecked exceptions. When to choose checked and unchecked exceptions

这里有一个关于何时选择已检查异常和何时选择未检查异常的问题。当选择选中的和未检查的异常时。

#3


1  

Below link says that openconnection method can throw an exception.

下面的链接说openconnection方法可以抛出一个异常。

If you are using this method, you must use catch or throw it again.

如果您正在使用此方法,您必须使用catch或再次抛出它。

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

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

Edit: Instead of throwing exception, try like this

编辑:像这样尝试,而不是抛出异常。

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

#4


1  

Since you are new to Java, I would suggest using Eclipse (an IDE) to edit your code. It will automatically make suggestions for you.

由于您是Java新手,所以我建议您使用Eclipse(一个IDE)来编辑您的代码。它会自动给你提建议。

In the searchButton actionListener "actionPerformed" call, you will need to edit your code as follows:

在searchButton actionListener“actionPerformed”调用中,您需要编辑您的代码如下:

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

});

});

All I did was add a try/catch handler because you've declared the "callUrl()" function as throwing an exception. I ran the above code using your pasted code - this works.

我所做的只是添加一个try/catch处理程序,因为您已经声明了“callUrl()”函数作为抛出异常。我使用您的粘贴代码运行上述代码——这是有效的。

Let me know if you need further help.

如果你需要进一步的帮助,请告诉我。

#5


1  

HttpURLConnection#openConnection throws an Exception, which callUrl() declares. initUI() calls callUrl() but does not declare the exception. This might help:

HttpURLConnection#openConnection抛出一个异常,callUrl()声明。initUI()调用callUrl(),但不声明异常。这可能帮助:

private void initUI() throws Exception {

Alternately, you could surround the HttpURLConnection#openConnection() call with a try/catch block:

另外,您可以使用try/catch块来包围HttpURLConnection#openConnection()调用:

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

#6


0  

Here is your error:

这是你的错误:

private void callUrl() throws Exception {

When you say that a method throws Exception then every caller must somehow handle that exception. There is hardly ever a need to say that a method throws Exception (which is the mother of all "checked" exceptions) vs some more precise condition, and, in particular, if the method only throws "unchecked" exceptions (subclasses of Error or RuntimeException) then there's no need to use the throws clause at all.

当您说一个方法抛出异常时,每个调用者都必须以某种方式处理这个异常。很少有需要说一个方法抛出异常(这是所有“检查”的例外)和一些更精确的条件,特别是,如果方法只抛出“unchecked”异常(错误或RuntimeException的子类),那么就没有必要使用抛出条款。

In the above case you appear to have some IOException possibilities, meaning you will need to catch or declare them, but it should be sufficient to say throws IOException vs throws Exception, or, probably better, catch IOException inside the method and handle it. (It's always best to handle an exception as close to the context of throwing it as possible.)

在上面的例子中,您似乎有一些IOException的可能性,这意味着您需要捕获或声明它们,但是它应该足以说明抛出IOException vs抛出异常,或者,可能更好,在方法中捕获IOException并处理它。(最好是处理一个异常,尽可能地接近抛出它的上下文。)

Hint: For a test case or "quick and dirty" program it's sufficient to say throws WhateverException on the main method, vs having to handle it there. (For any "real" application, of course, you should catch the exception and present a nicely formatted error message.)

提示:对于一个测试用例或“快速而肮脏”的程序,它足以说明在主方法上抛出任何异常,而vs必须在那里处理它。(当然,对于任何“真正的”应用程序,您应该捕获异常并呈现一个格式良好的错误消息。)

(And you can thank Mr. Goodenough for all of this mess.)

(你也可以感谢Mr. Goodenough所有这些乱七八糟的东西。)

#1


1  

I cut and pasted your code into Eclipse and it had me (by highlighting an error) put a try around the following:

我将您的代码剪切并粘贴到Eclipse中,它让我(通过高亮显示一个错误)在下面进行了尝试:

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

#2


2  

This is not quite specific to your question, but it will help you in understanding about the exception handling in java.

这并不是针对您的问题,但是它将帮助您理解java中的异常处理。

There are two types of exceptions

有两种类型的异常。

  • Checked exceptions
  • 已检查的异常
  • Unchecked exceptions
  • 未经检查的异常

Checked exceptions should be handled in code, that means you either need to handle with in the method or throw the exceptions so that the caller of the method will take care.

检查异常应该在代码中处理,这意味着您要么需要在方法中处理,要么抛出异常,以便方法的调用者会小心处理。

To catch the exception you need to use try and catch. If you don't want to handle the exception you can declare your method as throws SomeException so that caller would handle.

要捕获异常,您需要使用try和catch。如果您不想处理异常,则可以将方法声明为抛出异常,以便调用方处理。

For Example:

例如:

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

If you don't want to handle the exception (You make your method to throw the exception)

如果您不想处理异常(您使您的方法抛出异常)

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

Another best practice is, you can catch the checked exception and throw a Unchecked exception (RuntimeException) so that the caller of the method doesnt need to handle that. Spring uses this approach widely.

另一个最佳实践是,您可以捕获已检查的异常,并抛出一个未检查的异常(RuntimeException),以便该方法的调用方不需要处理该异常。Spring广泛使用了这种方法。

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

Here is a question on when to choose Checked exceptions and when to choose Unchecked exceptions. When to choose checked and unchecked exceptions

这里有一个关于何时选择已检查异常和何时选择未检查异常的问题。当选择选中的和未检查的异常时。

#3


1  

Below link says that openconnection method can throw an exception.

下面的链接说openconnection方法可以抛出一个异常。

If you are using this method, you must use catch or throw it again.

如果您正在使用此方法,您必须使用catch或再次抛出它。

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

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

Edit: Instead of throwing exception, try like this

编辑:像这样尝试,而不是抛出异常。

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

#4


1  

Since you are new to Java, I would suggest using Eclipse (an IDE) to edit your code. It will automatically make suggestions for you.

由于您是Java新手,所以我建议您使用Eclipse(一个IDE)来编辑您的代码。它会自动给你提建议。

In the searchButton actionListener "actionPerformed" call, you will need to edit your code as follows:

在searchButton actionListener“actionPerformed”调用中,您需要编辑您的代码如下:

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

});

});

All I did was add a try/catch handler because you've declared the "callUrl()" function as throwing an exception. I ran the above code using your pasted code - this works.

我所做的只是添加一个try/catch处理程序,因为您已经声明了“callUrl()”函数作为抛出异常。我使用您的粘贴代码运行上述代码——这是有效的。

Let me know if you need further help.

如果你需要进一步的帮助,请告诉我。

#5


1  

HttpURLConnection#openConnection throws an Exception, which callUrl() declares. initUI() calls callUrl() but does not declare the exception. This might help:

HttpURLConnection#openConnection抛出一个异常,callUrl()声明。initUI()调用callUrl(),但不声明异常。这可能帮助:

private void initUI() throws Exception {

Alternately, you could surround the HttpURLConnection#openConnection() call with a try/catch block:

另外,您可以使用try/catch块来包围HttpURLConnection#openConnection()调用:

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

#6


0  

Here is your error:

这是你的错误:

private void callUrl() throws Exception {

When you say that a method throws Exception then every caller must somehow handle that exception. There is hardly ever a need to say that a method throws Exception (which is the mother of all "checked" exceptions) vs some more precise condition, and, in particular, if the method only throws "unchecked" exceptions (subclasses of Error or RuntimeException) then there's no need to use the throws clause at all.

当您说一个方法抛出异常时,每个调用者都必须以某种方式处理这个异常。很少有需要说一个方法抛出异常(这是所有“检查”的例外)和一些更精确的条件,特别是,如果方法只抛出“unchecked”异常(错误或RuntimeException的子类),那么就没有必要使用抛出条款。

In the above case you appear to have some IOException possibilities, meaning you will need to catch or declare them, but it should be sufficient to say throws IOException vs throws Exception, or, probably better, catch IOException inside the method and handle it. (It's always best to handle an exception as close to the context of throwing it as possible.)

在上面的例子中,您似乎有一些IOException的可能性,这意味着您需要捕获或声明它们,但是它应该足以说明抛出IOException vs抛出异常,或者,可能更好,在方法中捕获IOException并处理它。(最好是处理一个异常,尽可能地接近抛出它的上下文。)

Hint: For a test case or "quick and dirty" program it's sufficient to say throws WhateverException on the main method, vs having to handle it there. (For any "real" application, of course, you should catch the exception and present a nicely formatted error message.)

提示:对于一个测试用例或“快速而肮脏”的程序,它足以说明在主方法上抛出任何异常,而vs必须在那里处理它。(当然,对于任何“真正的”应用程序,您应该捕获异常并呈现一个格式良好的错误消息。)

(And you can thank Mr. Goodenough for all of this mess.)

(你也可以感谢Mr. Goodenough所有这些乱七八糟的东西。)