不可编译的源代码-未报告的异常java.lang.exception;必须被抓住或宣布被抛出
我是JAVA新手,刚刚学习了JAVA的一些基础知识,现在我正在尝试学习一些高级JAVA,我不知道它的高级与否,但我尝试做的是,当我点击搜索按钮时,我将发送一个http调用,当我删除http请求代码时,或者当我删除搜索按钮代码时,它将单独工作,而不是一起工作 这是我的密码:不可编译的源代码-未报告的异常java.lang.exception;必须被抓住或宣布被抛出,java,exception-handling,try-catch,Java,Exception Handling,Try Catch,我是JAVA新手,刚刚学习了JAVA的一些基础知识,现在我正在尝试学习一些高级JAVA,我不知道它的高级与否,但我尝试做的是,当我点击搜索按钮时,我将发送一个http调用,当我删除http请求代码时,或者当我删除搜索按钮代码时,它将单独工作,而不是一起工作 这是我的密码: /* * To change this license header, choose License Headers in Project Properties. * To change this template fil
/*
* 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)
下面的链接说明openconnection方法可以引发异常 如果您正在使用此方法,则必须再次使用catch或throw 编辑:不要抛出异常,像这样尝试
private void callUrl() {
try {
// your stuff
} catch (Exception e) {
// print it for sure
}
}
下面的链接说明openconnection方法可以引发异常 如果您正在使用此方法,则必须再次使用catch或throw 编辑:不要抛出异常,像这样尝试
private void callUrl() {
try {
// your stuff
} catch (Exception e) {
// print it for sure
}
}
我将您的代码剪切并粘贴到Eclipse中,它让我(通过突出显示一个错误)尝试以下操作:
searchButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent event) {
try {
callUrl();
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
});
我将您的代码剪切并粘贴到Eclipse中,它让我(通过突出显示一个错误)尝试以下操作:
searchButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent event) {
try {
callUrl();
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
});
HttpURLConnection#openConnection抛出一个异常,callUrl()声明了该异常。initUI()调用callUrl(),但不声明异常。这可能有助于:
private void initUI() throws Exception {
或者,您可以使用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
HttpURLConnection#openConnection抛出一个异常,callUrl()声明了该异常。initUI()调用callUrl(),但不声明异常。这可能有助于:
private void initUI() throws Exception {
或者,您可以使用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
这并不是针对您的问题,但它将帮助您理解java中的异常处理 有两种类型的例外
- 检查异常
- 未检查的异常
try
和catch
。如果您不想处理异常,可以将您的方法声明为抛出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;
}
如果你不想处理异常(你让你的方法抛出异常)
另一个最佳实践是,您可以捕获已检查的异常并抛出未检查的异常(RuntimeException
),以便方法的调用方不需要处理该异常。Spring广泛使用这种方法
try {
.....
} catch (FileNotFoundException fne) {
//log fne
throw new RuntimeException(fne);
}
这里有一个关于何时选择选中的异常以及何时选择未选中的异常的问题 这对于您的问题不是很具体,但它将帮助您了解java中的异常处理 有两种类型的例外
- 检查异常
- 未检查的异常
try
和catch
。如果您不想处理异常,可以将您的方法声明为抛出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;
}
如果你不想处理异常(你让你的方法抛出异常)
另一个最佳实践是,您可以捕获已检查的异常并抛出未检查的异常(RuntimeException
),以便方法的调用方不需要处理该异常。Spring广泛使用这种方法
try {
.....
} catch (FileNotFoundException fne) {
//log fne
throw new RuntimeException(fne);
}
这里有一个关于何时选择选中的异常以及何时选择未选中的异常的问题 由于您是Java新手,我建议您使用Eclipse(IDE)来编辑代码。它会自动为您提供建议 在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();
}
}
}))
我所做的只是添加了一个try/catch处理程序,因为您已将“callUrl()”函数声明为引发异常。我使用粘贴的代码运行了上面的代码-这很有效
如果您需要进一步的帮助,请告诉我。因为您是Java新手,我建议您使用Eclipse(IDE)来编辑代码。它会自动为您提供建议 在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();
}
}
}))
我所做的只是添加了一个try/catch处理程序,因为您已将“callUrl()”函数声明为引发异常。我使用粘贴的代码运行了上面的代码-这很有效
如果您需要进一步帮助,请告诉我。以下是您的错误:
private void callUrl() throws Exception {
当您说一个方法抛出异常时,那么每个调用方都必须以某种方式处理该异常。几乎没有必要说一个方法抛出异常
(它是所有“已检查”异常的母亲)而不是更精确的条件,特别是,如果该方法只抛出“未检查”异常(错误或RuntimeException的子类),那么根本不需要使用抛出子句
在上面的例子中,您似乎有一些IOException的可能性,这意味着您需要捕获或声明它们,但是说抛出IOException
vs抛出异常
就足够了,或者说,更好的方法是在方法内部捕获IOException并处理它。(处理异常时最好尽可能接近抛出异常的上下文。)
提示:对于一个测试用例或“又快又脏”的程序,只要说在main
方法上抛出WhateverException
就足够了,而不是必须