gpt4 book ai didi

java - 源代码无法编译——未报告异常java.lang.Exception;必须被捕获或宣布被扔出

转载 作者:行者123 更新时间:2023-12-01 08:06:10 29 4
gpt4 key购买 nike

我是 JAVA 新手,刚刚学习了它的基础知识,现在我正在尝试学习一些高级 JAVA 我不知道它是否先进,但我想做的是当我单击“搜索”按钮时我将发送 1 个 http 调用,当我删除 http 请求代码或删除搜索按钮代码时,它会单独工作,但不能一起工作

这是我的代码:

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

最佳答案

这并不完全针对您的问题,但它将帮助您了解 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;
}

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

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

这里有一个关于何时选择 Checked 异常以及何时选择 Unchecked 异常的问题。 When to choose checked and unchecked exceptions

关于java - 源代码无法编译——未报告异常java.lang.Exception;必须被捕获或宣布被扔出,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21415948/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com