I am trying to handle the exceptions that are a part of the java.net package. I went through the documentation and I saw 12 exceptions belonging to that package, but I couldn't find the parent class of these exceptions.
So far what I have tried is:
catch(Exception e)
{
if(e instanceof org.openqa.selenium.WebDriverException)
sendException("Problem is with the selenium web driver");
else if(e instanceof java.net.Exception) //I need help with this line
sendException("There is some problem with the network");
}
After trying this, I get the following error message
unable to resolve class java.net.Exception
How can I catch the java.net exceptions?
First off, the reason that you can't catch java.net.Exception is that it doesn't exist! The actual Exception class java.lang.Exception but that is NOT the exception you should be catching.
So what should you catch?
Unfortunately, there there is no single supertype for all networking exceptions (and not non-networking exceptions). Most networking exceptions have java.io.IOException as an ancestor, but many IOException subclasses are declared in java.io and other places and have nothing to do with networking.
(One java.net.* exception that doesn't descend from IOException; i.e. java.net.URISyntaxException. But that is an unchecked exception, and it is not indicative of a "network problem".)
So one approach would be to catch IOException. You could further refine this by using reflection to get the package name of the exception class (see https://stackoverflow.com/a/57002571/139985); e.g.
} catch (org.openqa.selenium.WebDriverException e) {
sendException("Problem is with the selenium web driver");
} catch (IOException e) {
if (e.getClass().getPackage().startsWith("java.net"))
sendException("There is some problem with the network");
else {
throw e; // Or diagnose differently
}
}
But there is another wrinkle: even java.net.* exceptions don't necessarily indicate a "network problem". For example, if you get an UnknownHostException, that's probably not a problem with the network. It is more likely that you (or the user) have supplied the wrong hostname. Likewise, some flavors of ConnectException indicate that the network is fine, but the required remote service is not running on that host. It might be down, or you might have gotten the wrong host.
Finally, if you translate all java.net exceptions to a simple catch-all "network problem" message, you will be discarding information that could be used to diagnose the actual problem. So, I'd advise you not to try to do what you are proposing. Not even in a "friendly" user interface.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With