-4

I was reading a lesson about protocol, but I don't understand why use a try/catch to get an ipv4 address.

Code:

import java.net.Inet4Address;
import java.net.UnknownHostException;

public class P1 {
    public static void main(String[] args) {
        try{
            System.out.println(Inet4Address.getLocalHost().getHostAddress());
        }catch(UnknownHostException e){
            e.printStackTrace();
        }
    }
}
Cœur
  • 37,241
  • 25
  • 195
  • 267
  • Don't post screenshots of code. If you have a nice small self-contained piece of code, put it as text in your actual question. See [Images of code](http://idownvotedbecau.se/imageofcode) – khelwood Nov 27 '17 at 09:24
  • [how to ask](http://stackoverflow.com/help/how-to-ask) – Abhijeetk431 Nov 27 '17 at 09:29

1 Answers1

0

The signature of the method "getLocalHost" looks like this:

InetAddress java.net.InetAddress.getLocalHost() throws UnknownHostException

That is a so called "checked exception" and means that while executing the method an exception might occur (an UnknownHostException). So every caller of the method (in your example the main method) is supposed to handle that exception somehow. The designers of "getLocalHost" defined that this error is crucial and has to be handled by the caller, that's why they added "throws UnknownHostException".

When you use try/catch you can define in the catch part what should happen in case of an UnknownHostException.

For instance you could write an understandable message to the console and exit the application:

package com.example;

import java.net.Inet4Address;
import java.net.UnknownHostException;

public class P1 {

    public static void main(String[] args) {
        try {
            System.out.println(Inet4Address.getLocalHost().getHostAddress());
        } catch (UnknownHostException e) {
            System.err.println("An error occurred while fetching IP address");
            System.exit(1);
        }
    }

}

On the other hand you are not forced to handle the exception straight away. You can also define that your method throws an UnknownHostException as well. That means someone who calls your method has to deal with it. The caller of your method can also define that his/her method throws an UnknownHostException. And so on.

package com.example;

import java.net.Inet4Address;
import java.net.UnknownHostException;

public class P1 {

    public static void main(String[] args) throws UnknownHostException {
        System.out.println(Inet4Address.getLocalHost().getHostAddress());
    }

}

As the method is already the main entry point you can't bubble the exception up any further. This means that an UnknownHostException will appear in the console by default if you don't use try/catch.

JanTheGun
  • 2,165
  • 17
  • 25