Java Inetaddress, Swing extends, and throws Exception
In a project that I'm current working on, I'm using Eclipse with the Ji开发者_StackOverflow中文版gloo Gui Builder.
The builder creates the class with this class line:
public class ChatServer extends javax.swing.JFrame {
String fromclient;
String ToClient;
String serverName = InetAddress.getLocalHost().getHostAddress();
String clientName = "";
...
But Inetaddress gives an error that says "Unhandled exception type UnknownHostException".
Looking through one of the other tutorial codes that I'm trying to learn off, it has the "throws Exception" on the main class. I need it to have a "throws Exception" in the public class ChatServer because I require it to be a variable throughout the whole program.
Does anyone know the proper syntax or another alternative? Sorry to all, but I'm pretty new to Java.
Put the assignment of serverName in the constructor of ChatServer, where you either try-catch the exception yourself and do something appropriate or let the constructor throw an UnknownHostException (if possible). Maybe there is a constructor already in the class? If not, specify one with for example:
public ChatServer() {
try {
serverName = InetAddress.getLocalHost().getHostAddress();
} catch (UnknownHostException ex) {
// Maybe set serverName to something default
...
}
}
精彩评论