在我的Android Studio项目中,我发现很多"错误:(38,45)错误:未报告的异常IOException;必须被抓住或宣布被扔掉#34;错误。如何解决这些错误?
这是我的代码:
public class ActivityHome extends Activity {
private final static String QUEUE_NAME = "AndroidJava";
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ConnectionFactory factory = new ConnectionFactory();
factory.setHost("xx.xx.xx.xx");
Connection connection = factory.newConnection();
Channel channel = connection.createChannel();
channel.queueDeclare(QUEUE_NAME, false, false, false, null);
String message = "Hello Java!";
channel.basicPublish("", QUEUE_NAME, null, message.getBytes("UTF-8"));
System.out.println(" [x] Sent '" + message + "'");
channel.close();
connection.close();
}
}
答案 0 :(得分:0)
我建议通过Javadocs阅读ActivityHome.onCreate()
中使用的依赖关系来确定抛出IOException
的内容,特别是与数据库相关的javadoc。一旦确定了引发异常的内容,就可以使用try catch
块来解决可能出现的问题:
try{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ConnectionFactory factory = new ConnectionFactory();
factory.setHost("xx.xx.xx.xx");
Connection connection = factory.newConnection();
Channel channel = connection.createChannel();
channel.queueDeclare(QUEUE_NAME, false, false, false, null);
String message = "Hello Java!";
channel.basicPublish("", QUEUE_NAME, null, message.getBytes("UTF-8"));
System.out.println(" [x] Sent '" + message + "'");
channel.close();
connection.close();
} catch(IOException e) {
e.printStackTrace() //Or log it to a file, or clean up resources
}
或throws
强制任何调用你的方法代替处理它:
public onCreate(Bundle savedInstanceState) throws IOException {
//body
}
Java Guide to Exceptions有助于确定哪种更适合您的用例。