I am working with java.
I have one url as a input.I am trying to open url using java code.
I am using:
URL url=new URL("http://doctorwho.time-and-space.co.uk/index.php");
URLConnection conn=url.openConnection();
InputStream in=conn.getInputStream();
here I have passed one link as a input,but this website is unavailable.Here I want to throw an
exception on opening this url,but it is not throwing any exception,it is executing properly.
Please help me,how to catch this exception if website is unavailable.
Actually all of your lines can throw an exception:
java.net.URL.openConnection() throws IOException
java.net.URLConnection.getInputStream() throws IOException
java.net.URLConnection.getInputStream() throws IOException
You should handle these one by one, and if you encounter any of them, you should deal with the error in your own code. Maybe throw another exception, stop execution, anything you want. Probably you have a big try-catch (Exception e) around this block, which you should get rid of.
If you want to throw an exception, and not handling it in the function, use throws, and don't use try-catch:
public void foo() throws IOException
{
URL url=new URL("http://doctorwho.time-and-space.co.uk/index.php");
URLConnection conn=url.openConnection();
InputStream in=conn.getInputStream();
//...
}
You can wrap the IOException into your own.
public void fireURL(String pathToFireParam) throws CustomException
{
try{
URL url=new URL(pathToFireParam);
URLConnection conn=url.openConnection();
InputStream in=conn.getInputStream();
} catch(IOException ioexc){
throw new CustomException("Unavailable: "+ioexc.getMessage(),ioexc);
}
}
This code is indeed throwing an exception: IOException.
The best thing probably is to create an Exception class specific to this service that you recatch. To let the program take differents actions depending of the error (this can be just displaying a nice looking message instead of an hugly stacktrace), you can extends your base service exception with the specific exception.
So the base Exception :
public class MyServiceException extends Exception {
private static final long serialVersionUID = 1L;
public MyServiceException(String s, Throwable throwable) {
super(s, throwable);
}
}
The Exception that is thrown for all problem related to "stuff"
public class MyServiceStufFailedException extends MyServiceException {
private static final long serialVersionUID = 1L;
public MyServiceStufFailedException(String s, Throwable throwable) {
super(s, throwable);
}
}
And the code that load the XML file :
private void doStufWithURL(String fileURL) throws MyServiceStufFailedException {
try {
URL url=new URL(fileURL);
URLConnection conn=url.openConnection();
InputStream in=conn.getInputStream();
// Use input Stream too...
} catch (IOException exception) {
//Don't forget to put an explanation and the cause to help while debugging.
throw new MyServiceStufFailedException("IO Error while reading " + fileURL, exception);
}
}
Related
I have Jenkins plugin written in Java. I am capturing all the workflows of execution of plugin in a integer variable in three ways 0(2xx workflows), 1(4xx workflows), 2(5xx workflows) and sending them to SignalFX for metrics. Since this is not an API and errors will be mainly caught in try catch workflow.
I wanted to ask how to read error codes from exception class and categorize them in 2xx, 4xx or 5xx. Are there some rules which I can follow by?
try {
Thread.sleep(60 * 1000);
} catch (InterruptedException e) {
sendToSignalFX(0,data); // 0 means successful state
}
Some of the exceptions classes I will be using are -
Exception, IOException, InterruptedException, ParserConfigurationException, SAXException
I believe you may have to add a method to identify the failure reason from e.getMessage() for one OR have a custom exception to help with your case.
Also if it’s an HTTP request-related exception (from the error response code mentioned in the question details) or something, you may want to add a custom exception, instead of throwing the original exception. In the custom exception, you can add a custom field to get errorCode from the response code.
// MyCustomException.java
public class MyCustomException extends Exception {
String errorReason;
int errorCode;
public MyCustomException(Throwable throwable, String errorReason, int errorCode) {
super(errorReason, throwable);
this.errorReason = errorReason;
this.errorCode = errorCode;
}
}
And in your request handler code:
try {
// otherCode which might cause IOException
// ...
Response response = myHttpRequest();
if (!response.isSuccessful()) {
// identify the error code and set corresponding errorCode to MyCustomException. errorCode
int errorCode = 0;
// parse response.getStatusCode() or equivalent of the library and reassign the value of errorCode
throw new MyCustomException(e, e.getMessage(), errorCode);
}
// ...
// otherCode which might cause IOException
} catch (Exception | IOException e) {
throw new MyCustomException(e, e.getMessage(), 0);
}
I am trying to throw a timeout exception in the code below. I tried a simple condition but it's not the proper way.
My question is how can I distinct the timeout exception from SOAPException?
URL endpoint = new URL(null,
urlStr,
new URLStreamHandler() {
// The url is the parent of this stream handler, so must create clone
protected URLConnection openConnection(URL url) throws IOException {
URL cloneURL = new URL(url.toString());
HttpURLConnection cloneURLConnection = (HttpURLConnection) cloneURL.openConnection();
// TimeOut settings
cloneURLConnection.setConnectTimeout(10000);
cloneURLConnection.setReadTimeout(10000);
return cloneURLConnection;
}
});
try {
response = connection.call(request, endpoint);
} catch (SOAPException soapEx) {
if(soapEx.getMessage().contains("Message send failed")) {
throw new TimeoutExpirationException();
} else {
throw soapEx;
}
}
The following lines are from open jdk source code of call method. In the code they are only catching with Exception (also with chaining? comment). I don't think there is other way unless Oracle jdk handles this differently.
You can still try something like if(soapEx.getCause() instanceof SomeTimeoutException) (not sure if this will work)
try {
SOAPMessage response = post(message, (URL)endPoint);
return response;
} catch (Exception ex) {
// TBD -- chaining?
throw new SOAPExceptionImpl(ex);
}
If you want to check the source code HttpSoapConnection
After some hours of testing I found the proper way to distict the SOAPException from Timeout related exceptions. So the solution is to take the parent cause field of the exception and check if it's an instance of SocketTimeoutException.
try {
response = connection.call(request, endpoint);
} catch (SOAPException soapEx) {
if(soapEx.getCause().getCause() instanceof SocketTimeoutException) {
throw new TimeoutExpirationException(); //custom exception
} else {
throw soapEx;
}
}
I am new to android apps development. Recently,Im writing an application which able to show public ip based on Ipify. So far, i already:
Download the required jar file and put inside libs folder
I also compile file within gradle
Then i import required class it to my class
How to use Ipify, according to its website:
import org.ipify.Ipify;
public class HelloIP {
public static void main(String[] args) throws IOException {
System.out.println(Ipify.getPublicIp());
}
}
I write the following method to be invoked from another class:
public static String getPublicIp() throws IOException{
String ip = Ipify.getPublicIp();
return ip;
}
Another Class
//Get wifi
getWifiName wifiInfo = new getWifiName();
String myIP = wifiInfo.getPublicIp();
However, i keep getting:
Error:(52, 43) error: unreported exception IOException; must be caught
or declared to be thrown
I tried to modify the code and use the following try and catch, but still got the same error.
public static String getPublicIp() throws IOException{
String myip = Ipify.getPublicIp();
try{
return myip;
}
catch (IOException e){
System.out.println("General I/O exception: " + e.getMessage());
e.printStackTrace();
}
}
Im not too good in catch and throw exception, and already spent the whole day for this.I dont have idea anymore to fix this error..T.T
public static String getPublicIp() {
try{
return Ipify.getPublicIp();
}catch (IOException e){
System.out.println("General I/O exception: " + e.getMessage());
e.printStackTrace();
}
return null;
}
In case it didn't help, clean project in your IDE. You may have some data cached and it might be a reason.
Your problem is in another class! As you have declared the method getPublicIp() to throw IOException that class is afraid of receiving the Exception and therefor requests catching it.
In Java you have two types of Exceptions. Checked and unchecked. Checked Exceptions must be caught.
In Java Exceptions are used for marking unexpected situations. For example parsing non-numeric String to a number (NumberFormatException) or calling a method on a null reference (NullPointerException). You can catch them in many ways.
Unchecked Exceptions are those which extend RunTimeException. They are used for marking unexpected states usually caused by user's input. They shouldn't cause harm and should be worked out with business logic. You don't have to catch them, but sometimes you should.
On the other hand there are Checked Exceptions which mark dangerous situations. For example the application being unable to open a file. As those situations are found dangerous, you must catch them.
try{
//some code
} catch (NumberFormatException e1) {
e.printStackTrace() //very important - handles the Exception but prints the information!
} catch (NullPointerException e2) {
e.printStackTrace();
}
or using the fact, that they all extend Exception:
try {
//somecode
} catch (Exception e) {
e.printStackTrace;
};
or since Java 7:
try {
//somecode
} catch (NullPointerException | NumberFormatException e) {
e.printStackTrace;
};
java version "1.7.0_45"
Hello
I am initializing the class methods in the constructor. However, the new URL(uploadUrl) will throw an exception in the constructor. So if this happens the user shouldn't be able to continue. As the constructor cannot return anything, I am wondering that is the best way to handle this?
Many thanks for any suggestions,
public class MultipleFileTransfer {
private static final String TAG = MultipartUtility.class.getSimpleName();
private DataOutputStream dataOutputStream;
private FileInputStream fileInputStream;
private HttpURLConnection httpURLConnection;
private URL url;
public MultipleFileTransfer(final String uploadUrl) {
dataOutputStream = null;
fileInputStream = null;
httpURLConnection = null;
try {
url = new URL(uploadUrl);
} catch (MalformedURLException e) {
Log.wtf(TAG, e.getMessage()); /* <-- How to handle a failure */
}
}
/* Factory method that initializes the class methods and returns the class object */
public static MultipleFileTransfer getInstance(final String uploadUrl) {
/* Check that a valid url has been entered correctly */
if(!URLUtil.isValidUrl(uploadUrl)) {
Log.wtf(TAG, "Invalid url: " + uploadUrl);
return null;
}
return new MultipleFileTransfer(uploadUrl);
}
}
As the constructor cannot return anything, I am wondering that is the best way to handle this?
Typically, allow the exception to propagate to the caller, either directly or by wrapping it in your own higher-level abstraction exception. (In your case, just allowing it directly looks more appropriate.)
public MultipleFileTransfer(final String uploadUrl) throws MalformedURLException {
// -------------------------------------------------^
dataOutputStream = null;
fileInputStream = null;
httpURLConnection = null;
url = new URL(uploadUrl);
}
Since your instance isn't useful without the URL, it makes sense for construction to fail.
Or if you want to log it in the constructor (but if it's propagating, typically any logging if appropriate would be handled by the caller):
// Logging and re-throwing, but probably not recommended
public MultipleFileTransfer(final String uploadUrl) throws MalformedURLException {
// -------------------------------------------------^
dataOutputStream = null;
fileInputStream = null;
httpURLConnection = null;
try {
url = new URL(uploadUrl);
} catch (MalformedURLException e) {
Log.wtf(TAG, e.getMessage());
throw e; // <== Rethrowing
}
}
I can think of two decent ways to handle the situation:
(1) Let the constructor throw an exception. Either rethrow the same exception after logging, or throw a different exception. If the exception it throws isn't a RuntimeException (and MalformedURLException is not a RuntimeException), you'll need to add a throws clause to the constructor.
(2) Let the constructor create an object anyway, but mark it as an "invalid" object that cannot be used. I'd add an isValid() or isInvalid() method so that the caller can query whether it's valid. Other methods should throw IllegalStateException if they're called on an invalid object.
I don't think one is clearly better than the other. It depends on preference and perhaps on the design of the rest of the program.
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!