Jump to content

If isReachable throws an IOException in Java, what is the right step to do and why?

 Share

Go to solution Solved by Sauron,

Read the documentation: https://docs.oracle.com/javase/1.5.0/docs/api/java/net/InetAddress.html#isReachable(int)

Quote

Throws:

        IOException - if a network error occurs

so all you can know of the exception is that there was a network error. This is what you should write in your debug message. Depending on what you're trying to do it could be useful to add information on which connection failed with this error.

If isReachable throws an IOException in Java, what is the right step to do and why?
The application, I believe, should halt the process and output the system message: the host is not accessible. Because isReachable throws an IOException, the host cannot be reached. 
But I'm not sure what the solution is. I would be grateful if you could assist me.
According to what I've read from here, a return result of false implies a failure to reach the host in question, whereas IOException suggests a vague "network fault," which means something like the OS detected an uncommon network problem. Is that right?

 

Link to comment
Share on other sites

Link to post
Share on other sites

Read the documentation: https://docs.oracle.com/javase/1.5.0/docs/api/java/net/InetAddress.html#isReachable(int)

Quote

Throws:

        IOException - if a network error occurs

so all you can know of the exception is that there was a network error. This is what you should write in your debug message. Depending on what you're trying to do it could be useful to add information on which connection failed with this error.

Don't ask to ask, just ask... please 🤨

sudo chmod -R 000 /*

What is scaling and how does it work? Asus PB287Q unboxing! Console alternatives :D Watch Netflix with Kodi on Arch Linux Sharing folders over the internet using SSH Beginner's Guide To LTT (by iamdarkyoshi)

Sauron'stm Product Scores:

Spoiler

Just a list of my personal scores for some products, in no particular order, with brief comments. I just got the idea to do them so they aren't many for now :)

Don't take these as complete reviews or final truths - they are just my personal impressions on products I may or may not have used, summed up in a couple of sentences and a rough score. All scores take into account the unit's price and time of release, heavily so, therefore don't expect absolute performance to be reflected here.

 

-Lenovo Thinkpad X220 - [8/10]

Spoiler

A durable and reliable machine that is relatively lightweight, has all the hardware it needs to never feel sluggish and has a great IPS matte screen. Downsides are mostly due to its age, most notably the screen resolution of 1366x768 and usb 2.0 ports.

 

-Apple Macbook (2015) - [Garbage -/10]

Spoiler

From my perspective, this product has no redeeming factors given its price and the competition. It is underpowered, overpriced, impractical due to its single port and is made redundant even by Apple's own iPad pro line.

 

-OnePlus X - [7/10]

Spoiler

A good phone for the price. It does everything I (and most people) need without being sluggish and has no particularly bad flaws. The lack of recent software updates and relatively barebones feature kit (most notably the lack of 5GHz wifi, biometric sensors and backlight for the capacitive buttons) prevent it from being exceptional.

 

-Microsoft Surface Book 2 - [Garbage - -/10]

Spoiler

Overpriced and rushed, offers nothing notable compared to the competition, doesn't come with an adequate charger despite the premium price. Worse than the Macbook for not even offering the small plus sides of having macOS. Buy a Razer Blade if you want high performance in a (relatively) light package.

 

-Intel Core i7 2600/k - [9/10]

Spoiler

Quite possibly Intel's best product launch ever. It had all the bleeding edge features of the time, it came with a very significant performance improvement over its predecessor and it had a soldered heatspreader, allowing for efficient cooling and great overclocking. Even the "locked" version could be overclocked through the multiplier within (quite reasonable) limits.

 

-Apple iPad Pro - [5/10]

Spoiler

A pretty good product, sunk by its price (plus the extra cost of the physical keyboard and the pencil). Buy it if you don't mind the Apple tax and are looking for a very light office machine with an excellent digitizer. Particularly good for rich students. Bad for cheap tinkerers like myself.

 

 

Link to comment
Share on other sites

Link to post
Share on other sites

2 hours ago, walihak said:
If isReachable throws an IOException in Java, what is the right step to do and why?

 

That depends on your use case.

 

In a server application it may be acceptable to shut down as a result. But more likely you'd log the issue, continue running and try again at a later date.

 

For a UI application, I'd expect it to tell me somethink like "I couldn't reach X, check your network connection" then offer me a way to retry.

Remember to either quote or @mention others, so they are notified of your reply

Link to comment
Share on other sites

Link to post
Share on other sites

6 hours ago, walihak said:

should halt the process

Generally you don't want your program to just bomb to the desktop when an exception is thrown.

 

That is actually why exceptions exist.

 

You should wrap the offending code in a try catch, and handle the exception. To figure out why the exception is being thrown you will have to debug your code.

 

Do a stacktrace, see where the failure point is and either correct that, or perform an action in your catch that resolves the problem.

 

Don't just swallow the exception and don't just bomb your software.

If your question is answered, mark it so.  | It's probably just coil whine, and it is probably just fine |   LTT Movie Club!

Read the docs. If they don't exist, write them. | Professional Thread Derailer

Desktop: i7-8700K, RTX 2080, 16G 3200Mhz, EndeavourOS(host), win10 (VFIO), Fedora(VFIO)

Server: ryzen 9 5900x, GTX 970, 64G 3200Mhz, Unraid.

 

Link to comment
Share on other sites

Link to post
Share on other sites

1 hour ago, Takumidesh said:

Generally you don't want your program to just bomb to the desktop when an exception is thrown.

There are rare exceptions (no pun intended): If you have a server application with an invalid configuration, it may be acceptable to refuse to start. Or if you depend on a database and if that isn't reachable you can't do anything useful anyway and continuing to run could even result in data loss. But as a rule of thumb you should handle exceptions as gracefully as possible.

 

In the case of isReachable, you can think of it like this:

  • true –> the remote machine is reachable
  • false –> the remote machine is unreachable, but the local network is fine
  • exception –> the local network is not fine

As I said above, how you handle this case is up to you. In most cases you want to tell the user about it, so they can fix their network setup.

Remember to either quote or @mention others, so they are notified of your reply

Link to comment
Share on other sites

Link to post
Share on other sites

Like eigen said, it all really depends on the use case...but even then the exception should be dealt with and handled gracefully (even if it means closing the program down).  I don't really think there would be any real case where you would want the exception not to be handled (and allowed to actually crash the program).  [i.e. if the program needs to stop processing if it exists, it should still handling it properly instead of just crashing itself]

 

 

 

On a side note, not relating the to topics what to do, I really do dislike the use of exceptions the way they are implemented (like for myself Java's isReachable should either true or false and not throw an exception especially when the exception essentially means that it's not reachable).  For myself it just feels as though exceptions are just a way to "send" more things when it fails instead of resorting to enums or similar...which then just results in the code that calls isReachable to be tailored in a way that makes it a lot less readable.  i.e. isReachable should return True/False but if it's important enough to know the why it wasn't reachable (like it returned false) then they should just allow a secondary parameter to get that information (instead of relying on a throw exception to relay information)

3735928559 - Beware of the dead beef

Link to comment
Share on other sites

Link to post
Share on other sites

12 hours ago, wanderingfool2 said:

On a side note, not relating the to topics what to do, I really do dislike the use of exceptions the way they are implemented (like for myself Java's isReachable should either true or false and not throw an exception especially when the exception essentially means that it's not reachable).

I tend to disagree. Exceptions allow for better separation of business logic and error handling. If you aren't able to deal with the exception right away, you can let it bubble up to a place that can. It's also much easier to ignore error codes (eh, that case will never happen…). There are some good answers/reasons given here: https://stackoverflow.com/a/100395

 

In the case of isReachable I think there's a technical difference between "the server did not reply" and "I don't actually know what the server's status is because you are offline". The first case is an expected answer, the second case is an exceptional circumstance that the user should know about/fix.

 

You could handle this particular case with an enum, but that may lead to cases where you now need to deal with this error in a place you aren't actually prepared to do so. Which means you now need to bubble up the error yourself, potentially including it in places that should return a business object. So you now need a wrapper object that either include the object or an error code and so on. I'd rather have a method that promises a non-null return value and throws than this.

Remember to either quote or @mention others, so they are notified of your reply

Link to comment
Share on other sites

Link to post
Share on other sites

6 minutes ago, Eigenvektor said:

I tend to disagree. Exceptions allow for better separation of business logic and error handling. If you aren't able to deal with the exception right away, you can let it bubble up to a place that can. It's also much easier to ignore error codes (eh, that case will never happen…). There are some good answers/reasons given here: https://stackoverflow.com/a/100395

I'm not against exceptions outright, but in the case of isReachable where a true/false return makes sense to return false on error and then yes deal with it right then and there (or in that case if a complex type is being thrown you throw an exception).  Like hypothetically if you just needed to know if something was reachable (didn't care whether or not it's valid or not) you have to now nest isReachable within it's try catch statement.

3735928559 - Beware of the dead beef

Link to comment
Share on other sites

Link to post
Share on other sites

34 minutes ago, wanderingfool2 said:

I'm not against exceptions outright, but in the case of isReachable where a true/false return makes sense to return false on error and then yes deal with it right then and there (or in that case if a complex type is being thrown you throw an exception).  Like hypothetically if you just needed to know if something was reachable (didn't care whether or not it's valid or not) you have to now nest isReachable within it's try catch statement.

I mean if you really don't care that it's not reachable because your network is down (rather than the server being down), you could always add a very thin wrapper around it that catches the exception and returns false. But I would assume in most cases you do care, because it's a user fixable error vs a server side error.

Remember to either quote or @mention others, so they are notified of your reply

Link to comment
Share on other sites

Link to post
Share on other sites

2 hours ago, wanderingfool2 said:

I'm not against exceptions outright, but in the case of isReachable where a true/false return makes sense to return false on error and then yes deal with it right then and there (or in that case if a complex type is being thrown you throw an exception).  Like hypothetically if you just needed to know if something was reachable (didn't care whether or not it's valid or not) you have to now nest isReachable within it's try catch statement.

but now you have a boolean value and that is all, you don't have any extra info, any methods calling isReachable have to also do something with this boolean return value (and in turn any method calling them)

 

An exception gives you valuable info like a stacktrace, as well as things finally, to gracefully handle a shutdown.

 

a simple bool greatly reduces the available options, and you often would have to implement polymorphic overloads, or psuedo try catch (if !IsReachable) handleIt();

 

If your question is answered, mark it so.  | It's probably just coil whine, and it is probably just fine |   LTT Movie Club!

Read the docs. If they don't exist, write them. | Professional Thread Derailer

Desktop: i7-8700K, RTX 2080, 16G 3200Mhz, EndeavourOS(host), win10 (VFIO), Fedora(VFIO)

Server: ryzen 9 5900x, GTX 970, 64G 3200Mhz, Unraid.

 

Link to comment
Share on other sites

Link to post
Share on other sites

13 minutes ago, Takumidesh said:

but now you have a boolean value and that is all, you don't have any extra info, any methods calling isReachable have to also do something with this boolean return value (and in turn any method calling them)

 

An exception gives you valuable info like a stacktrace, as well as things finally, to gracefully handle a shutdown.

 

a simple bool greatly reduces the available options, and you often would have to implement polymorphic overloads, or psuedo try catch (if !IsReachable) handleIt();

 

If it's important enough where you have a failing out where you need an exception like that, I would argue that you should be returning an enum type instead of a boolean type then.  It also means not having look up what exceptions something throws along with the reasons why it might throw the exception.  It gives you the option to also then quickly ignore it.

 

Generally speaking you could do effectively the same thing but have the implementation as cleaner code.

Spoiler
public enum RESPONSE_TYPE {
	SUCCESS,
    FAILURE,
    INVALID_NETWORK
}

void example1() {
    if(isReachable() == RESPONSE_TYPE.SUCCESS) {
    	xyz
    }
    else {
    	abc
    }
}

void tryexample1() {
	flag_successful = false
	try {
    	if(isReachable())
        	flag_successful = true
        	xyz
    }catch (exception e) {
    }
    if(!flag_successful)
    	abc
}

 

 

3735928559 - Beware of the dead beef

Link to comment
Share on other sites

Link to post
Share on other sites

7 hours ago, wanderingfool2 said:

If it's important enough where you have a failing out where you need an exception like that, I would argue that you should be returning an enum type instead of a boolean type then.  It also means not having look up what exceptions something throws along with the reasons why it might throw the exception.  It gives you the option to also then quickly ignore it.

 

Generally speaking you could do effectively the same thing but have the implementation as cleaner code.

But right now you only have three possible return values. You can have multiple different exceptions containing a lot more information other than just "invalid_network". So you'll quickly end up with a very large enum.

 

A success-flag is not how you'd normally handle these things. Your business logic takes place between try-catch, not after it.

public enum ResponseType {
    SUCCESS,
    FAILURE,
    INVALID_NETWORK
}

void isReachableErrorCode() {
    final var result = isReachable();

    if(result == SUCCESS) {
        // handle success case
    } else if (result == FAILURE) {
        // handle unreachable case
    } else {
        // handle error case(s)
    }
}

void isReachableTryCatch() {
    try {
        if (isReachable()) {
            // success case
        } else {
            // unreachable case
        }
    } catch (UnknownHostException e) {
        // error case 1
    } catch (… e) {
        // error case 2
    }
}

This is what I mean by separation of business logic and error handling logic. And if you're not able to properly handle the error in the current method, it's easy to let it bubble up to a place where you can. That's a lot more difficult with a return code. Think about a case like this one:

@NonNull
BusinessObject isReachableTryCatch() throws NetworkError {
    if (isReachable()) {
        // some server connection stuff
        // some requests…
        return new BusinessObject(serverResponse);
    } else {
        return new BusinessObject(defaultValue);
    }
}

You can't really do this if isReachable() returns an error code rathern than throwing an exception, except throwing your own exception that now contains not much useful information.

Remember to either quote or @mention others, so they are notified of your reply

Link to comment
Share on other sites

Link to post
Share on other sites

7 hours ago, Eigenvektor said:

it's easy to let it bubble up to a place where you can

key point here.

 

Exceptions are framework level and allow for much more sophisticated error handling. Exceptions are also OOP, you can define custom ones, extend them etc.

 

 

 

If your question is answered, mark it so.  | It's probably just coil whine, and it is probably just fine |   LTT Movie Club!

Read the docs. If they don't exist, write them. | Professional Thread Derailer

Desktop: i7-8700K, RTX 2080, 16G 3200Mhz, EndeavourOS(host), win10 (VFIO), Fedora(VFIO)

Server: ryzen 9 5900x, GTX 970, 64G 3200Mhz, Unraid.

 

Link to comment
Share on other sites

Link to post
Share on other sites

4 hours ago, Takumidesh said:

Exceptions are also OOP, you can define custom ones, extend them etc.

This. Exceptions are often hierarchical (e.g. IOException –> UnknownHostException), which makes filtering them much more flexible. You can extend existing hierarchies with your own without breaking existing code that expects to catch the base class. You can also add additional information to exceptions (yes technically you could with enums, but then every instance of that enum will need to provide that info, whether it makes sense or not).

 

In my eyes it would also be inconsistent to throw exceptions in one case and return error codes in others. When I'm asking whether a server is reachable, I'm really only expecting two answers, yes or no. Any other answer is unexpected/exceptional and warrants an exception.

 

While you can communicate similar information with error codes to some degree, I think you'd quickly end up with a ton of different ones or very generic ones that contain states that can't ever occur in certain cases.

 

For example it would make sense for isReachable and sendEmail to both throw an UnknownHostException. But the enum "Yes, No, Unknown_Host" that makes sense for isReachable makes no sense for sendEmail. You would probably want something like "Accepted, Rejected, …, Unknown_Host" as possible results. So you either end up with a ton of redundant states in different enums, or you create some God-enum that covers a million possible cases.

 

And if your program crashes as a result of an unhandled error code, you're often left with nothing other than some numerical value. In Java you'll end up with a stack trace that will help you find the cause much more quickly.

 

In my eyes it makes sense to use exceptions everywhere. You can always dump them down to error codes, if the additional information isn't needed. The reverse wouldn't really work. If you go from an error code to an exception, the additional information an exception can provide (e.g. stack trace) isn't there to begin with.

 

Here's another way you could do it for the example above, if you really don't care about why the server isn't reachable:

enum ServerStatus {
    UP,
    DOWN,
    INDETERMINATE,
}

@NonNull
ServerStatus getServerStatus() {
    try {
        return isReachable()
            ? ServerStatus.UP
            : ServerStatus.DOWN;
    } catch (Exception e) {
        return ServerStatus.INDETERMINATE;
    }
}

void isReachableTryCatch() {
    if (getServerStatus() == ServerStatus.UP) {
        // success case
    } else {
        // unreachable case
    }
}

 

Remember to either quote or @mention others, so they are notified of your reply

Link to comment
Share on other sites

Link to post
Share on other sites

On 1/25/2023 at 5:56 AM, Takumidesh said:

key point here.

 

Exceptions are framework level and allow for much more sophisticated error handling. Exceptions are also OOP, you can define custom ones, extend them etc.

Again, I'm not against exceptions.  I just don't feel that isReachable should be one that would throw an exception in the cases it does

3735928559 - Beware of the dead beef

Link to comment
Share on other sites

Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now
 Share


×