Java: Cannot initialize InetAddress - java

I can't seem to be able to initialize InetAddress object for some reason, I looked at the documentation and it is exactly as how I use it.
InetAddress firstMachineAddress = InetAddress.getByName("129.26.70.95");
InetAddress secondMachineAddress = InetAddress.getByName("129.26.70.108");
And Eclipse says:
Default constructor cannot handle exception type UnknownHostException thrown by implicit super constructor. Must define an explicit constructor
What the heck is wrong?

Your code seems to be in a class's constructor which is extended by another class, like so:
import java.net.*;
class SuperclassWithUnknownHostException {
public SuperclassWithUnknownHostException() throws UnknownHostException {
InetAddress firstMachineAddress = InetAddress.getByName("129.26.70.95");
InetAddress secondMachineAddress = InetAddress.getByName("129.26.70.108");
}
}
class SubclassCannotHandleException extends SuperclassWithUnknownHostException {
}
You need to add a default constructor to the subclass which throws the exception:
class SubclassCannotHandleException extends SuperclassWithUnknownHostException {
public SubclassCannotHandleException() throws UnknownHostException {
}
}

Are you handling the UnknownHostException thrown by the method you call?
InetAddress firstMachineAddress;
try {
firstMachineAddress = InetAddress.getByName("129.26.70.95");
} catch (UnknownHostException e) {
// print exception, throw error,
// try something else etc.
}

The inetAddress object throws an exception for one, so you will need to wrap a try-catch around it or have your method throw an exception as well. Also I believe you are getting the error because there is an exception coming back that you are not handling. The getByName() method uses the a string parameter of the name of the webaddress like www.google.com or www.amazon.com and so forth.
try{
InetAddress Address = InetAddress.getByName("www.google.com");
System.out.println(Address);
}catch(UnknownHostException e){
e.printStackTrace();
}
This displays www.google.com/64.233.177.147

Related

Class body - Call function to instantiate variable (unhandled exception type)

I'm having a small issue with my java code.
public class test {
static char[] pass = getMac(); // getting error on this line
public static char[] getMac() throws UnknownHostException
{
...code...
return x;
}
}
I am already throwing the exception in the method but i'm getting the error on this line too :
static char[] pass = getMac(); // getting error on this line
unhandled Exception Type : unknownHostException
is there any way to fix this ?
Thanks
I have tried :
try
{
static char[] pass = getMac();
}
catch (UnknownHostException e)
{
.....
}
but it doesn't work in the main class .
I am already throwing the exception in the method...
Right. That's the problem. By saying that the method throws that exception, you're forcing the calling code to handle it. Java's class initialization code isn't going to handle it for you, so you're getting an unhandled exception error.
Either handle it in the method, or defer initializing that static field until a time when you can handle it*. Note that static initializer blocks are allowed to include flow logic, so that's also an option.
Handling it in the method:
public static char[] getMac()
{
try {
// ...
return x;
}
catch (UnknownHostException e) {
// Appropriate handling
return null; // Or whatever's appropriate
}
}
Using a static initializer block:
public class test {
static char[] pass;
static {
try {
// ...
pass = x;
}
catch (UnknownHostException e) {
// Appropriate handling
pass = null; // Or whatever's appropriate
}
}
}

Java RMI proxy-casting issue

I'm trying to get a RMI program to work. So far, the server starts up correctly but the client fails casting the remote object to the interface.
Exception in thread "AWT-EventQueue-0" java.lang.ClassCastException:
com.sun.proxy.$Proxy0 cannot be cast to MonitorClient.InterfaceMonitor
All other answers I've found are for cases where the end user has cast the equivalent of InterfaceMonitorImpl (unknown to the client) instead of the Interface instead. This is not my case and I'm really at a loss here — RMI is nightmare-ish.
Server side
Main:
InterfaceMonitor obj;
try {
LocateRegistry.createRegistry(1099);
InterfaceMonitor stub = (InterfaceMonitor) UnicastRemoteObject.exportObject(new InterfaceMonitorImpl(), 0);
Registry registry = LocateRegistry.getRegistry();
registry.bind("imon", stub);
System.out.println("Server ready");
} catch (RemoteException | AlreadyBoundException ex) {
System.out.println("Server error: " + ex.toString());
}
InterfaceMonitor.java:
public interface InterfaceMonitor extends Remote {
int checkAge() throws RemoteException;
}
InterfaceMonitorImpl.java:
public class InterfaceMonitorImpl implements InterfaceMonitor {
public InterfaceMonitorImpl() throws RemoteException {
}
#Override
public int counter() throws RemoteException {
return 10;
}
}
Client side
try {
Registry reg = LocateRegistry.getRegistry(null);
InterfaceMonitor im = (InterfaceMonitor) reg.lookup("imon");
int counter = im.counter();
System.out.println("Counter: " + counter);
} catch (NotBoundException | RemoteException ex) {
Logger.getLogger(MonitorGUI.class.getName()).log(Level.SEVERE, null, ex);
}
The InterfaceMonitor.java is also on the client side.
Thanks for your time!
Obviously you must have two copies of InterfaceMonitor: one in MonitorClient and one in what may be something like MonitorServer. That makes two different classes. Not two copies of the same class. The class name, package, method declarations, inheritance, ... all have to be the same.

How to automatically initialize a static variable that call InetAddress.getLocalHost()?

following this short tutorial http://www.rgagnon.com/javadetails/java-0095.html I am trying to get my client IP Address.
The only difference from the tutorial is that I want that my IP address is put inside a static variable so I do in the following way:
private static InetAddress thisIp = InetAddress.getLocalHost();
But Eclipse give me the following error message: Unhandled exception type UnknownHostException
So, I think, that the problem is that I can't call this code:
InetAddress.getLocalHost();
into a static variable but I have first to declare the static variable and then initialize it into every method that use it.
The problem that I need it into a JUnit test and this is very bad initialize it every time into all #test method !!!
So, what can I do to avoid initializing it in every test method? There is some other way to initialize it only once? Can I create a initialization method that will automatically execute at the beginning when I run my test class? How?
Tnx
Andrea
Try to initialize on static block,
private static InetAddress thisIp;
static{
try {
thisIp = InetAddress.getLocalHost();
} catch (UnknownHostException ex) {
}
}
You can use a static initialization block:
class YourClass {
private static InetAddress thisIp;
static {
try {
thisIp = InetAddress.getLocalHost();
} catch(Exception ex) {
Logger.log(ex);
} finally {
...
}
}
...
}
This block can go at any point in the class, outside of any method.

chaining constructors in Java without throwing exceptions from the default constructor

I've read this: Can I use throws in constructor? -- which gave me the right idea, and led me to one answer, but was not very explicit. I've also read several others, but could not find my answer. To recap what I've learned for context, essentially, this will not compile...
public ExampleClass(String FileName)
{
this(new FileInputStream(FileName));
}
public ExampleClass(FileInputStream FileStream)
{
DoSomethingToSetupBasedUponFileStream(FileStream);
}
...because the FileInputStream constructor (called from the String Constructor) may throw a FileNotFoundException. You can still create the constructor by making it throw the same exception as follows:
public ExampleClass(String FileName) throws FileNotFoundException
{
this(new FileInputStream(FileName));
}
My question is related to a default constructor (no arguments) that would simply use a default filename String constant:
public ExampleClass() throws FileNotFoundException
{
this(DEFAULT_FILE_NAME);
}
This would chain the constructors as:
ExampleClass() --> ExampleClass(<String>) --> ExampleClass(<InputFileStream>)
In a case like this, is it possible to use a default value (static final class member) in the default constructor, to instantiate (further down the chain) a FileInputStream, but not have to use the throws FileNotFoundException code (which would require someone using the class to either re-throw or handle the exception?
If I could do something like the following, I would handle the exception myself:
public ExampleClass()
{
try
{
this(DEFAULT_FILE_NAME);
}
catch (Exception e)
{
DoSomethingToHandleException(e);
}
}
...However, as far as I know this is not possible, because the "Constructor call must be the first statement in a constructor"
Being more used to .Net at this point, I've never been forced to deal with exceptions if I didn't really want to... :D
Refactor your file construction code out of your constructor, so you could do something like this --
public ExampleClass() {
try {
fileInputStreamMethod(DEFAULT_FILE);
}
catch(Exception e) {
...
}
public ExampleClass(String fileName) throws Exception {
fileInputStreamMethod(fileName);
}
private void fileInputStreamMethod(String fileName) throws Exception {
// your file handling methods
}
You are correct that you cannot catch an exception from the call to this(...).
You could use a static method to produce what you want:
static ExampleClass createDefault()
{
try
{
return new ExampleClass(DEFAULT_FILE_NAME);
}
catch(Exception e)
{
DoSomethingToHandleException(e)
}
}
You could do something like this:
public ExampleClass(String FileName)
{
this(getStream(FileName));
}
private static FileInputStream getStream(String name) {
try {
return new FileInputStream(name);
} catch (Exception e) {
// log error
return null;
}
}
The real question is, why would you not want to throw an exception? How should your program behave if the file cannot be opened? I think it would be unusual that you would want it to proceed as if there were no problem. Quite likely, the null input stream will cause grief later on.
In general, you're better off throwing an exception as close to the source of an error as possible.
Basically what you have to do is do the work that your constructor has to do in a different method(something that's not a constructor) and then use it in the default constructor. But am not sure how useful this technique is in your scenario.
cheers!

Java Inetaddress, Swing extends, and throws Exception

In a project that I'm current working on, I'm using Eclipse with the Jigloo 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
...
}
}

Categories

Resources