I have a method which needs to return a JSONObject:
public JSONObject getDayJson(Date date) {
...
a few lines of code
...
return new JSONObject("..");
}
However this gives me an error as I need to catch any exceptions which may occur as a result of instantiating the JSONObject:
public JSONObject getDayJson(Date date) {
try {
...
a few lines of code
...
return new JSONObject("..");
} catch (Exception e) {
// need a return statement here!
}
}
This creates another error as in the catch block I am not returning the correct object type which is a JSONObject. If I do instantiate another JSONObject in the catch I need to nest another catch statement?!
You should better think what you want to do if an exception happens, but one option is to force a non exception calling constructor.
public JSONObject getDayJson(Date date) {
try {
...
a few lines of code
...
return new JSONObject("..");
} catch (Exception e) {
// doesn't throw another exception
return new JSONObject(new HashMap());
}
}
Related
This is a sample block from my code.
...
try {
race.setDate(new Date(dateFormat.parse(entry[5]).getTime()));
race.setTime(Time.valueOf(entry[6]));
race.setFp1Date(new Date(dateFormat.parse(entry[8]).getTime()));
race.setFp1Time(Time.valueOf(entry[9]));
race.setFp2Date(new Date(dateFormat.parse(entry[10]).getTime()));
race.setFp2Time(Time.valueOf(entry[11]));
race.setFp3Date(new Date(dateFormat.parse(entry[12]).getTime()));
race.setFp3Time(Time.valueOf(entry[13]));
race.setQualiDate(new Date(dateFormat.parse(entry[14]).getTime()));
race.setQualiTime(Time.valueOf(entry[15]));
race.setSprintDate(new Date(dateFormat.parse(entry[16]).getTime()));
race.setSprintTime(Time.valueOf(entry[17]));
} catch (ParseException e) {
throw new RuntimeException(e);
}
...
Here every line in the try block can throw exception. According to my requirement if entry[i] is unparsable then the setter should set the value as null rather than throwing the exception. Putting every line in a try-and-catch block doesn't seem an optimal solution.
How can I optimally handle this situation rather than checking the value of entry[i] in every line?
Write a function which will catch a ParseException and return null:
static <T> T parseOrNull(Supplier<T> parser) {
try {
return parser.get();
} catch (ParseException e) {
return null;
}
}
Then call it in each of your lines:
...
race.setDate(parseOrNull(() -> new Date(dateFormat.parse(entry[5]).getTime())));
...
You can introduce new interface
interface Parser<T> {
T parse(String value) throws ParseException;
}
then create helper function
private static <T> void safeSet(Consumer<T> c, Parser<T> parser, String value){
try {
c.accept( parser.parse(value));
} catch (ParseException e) {
// log parse error
}
}
and use it in a following way:
safeSet( race::setDate, x-> new Date(dateFormat.parse(x).getTime()), entry[5]);
Additional bonus you can reuse parsers:
Parser<Date> dateParser = x -> new Date(dateFormat.parse(x).getTime());
safeSet(race::setDate, dateParser, entry[5]);
safeSet(race::setFp1Date, dateParser, entry[8]);
I have a string variable that has a full qualified exception name. I want to check in catch block if exceptions occur whether it is an instance of exception that mentioned in string or not. How to solve that
String stringEx = "org.hibernate.StaleStateException";
try {
// program
} catch (Exception ex) {
if (e instanceof stringEx) { //<-- How to convert string to exception class
// do specific process
}
}
Maybe you need this:
String stringEx = "org.hibernate.StaleStateException";
try {
// program
} catch (Exception ex) {
if (Class.forName(stringEx).isInstance(ex)) {
// do specific process
}
}
I am contemplating throwing a RuntimeException inside the catch block to solve the missing return statement.
What would be way to handle this situation?
I think throwing an exception of some kind instead of return some meaningless value. .
private String tryObjMapper(Object obj) {
try {
return objectMapper.writeValueAsString(obj);
} catch (JsonProcessingException e) {
e.printStackTrace();
}
//missing return statement
}
It depends on what you want to be the fallback/default value or error handling
You have 2 main options (with 2 sub options):
1.A.Throw the exception:
private String tryObjMapper(Object obj) throws JsonProcessingException {
return objectMapper.writeValueAsString(obj);
}
1.B.Rethrow RuntimeException (or custom unchecked exception)
private String tryObjMapper(Object obj) {
try {
return objectMapper.writeValueAsString(obj);
} catch (JsonProcessingException e) {
e.printStackTrace();
throw new RuntimeException("Failed to map obj +" obj, e);
}
}
2.A.Define a default value on error
private String tryObjMapper(Object obj) {
try {
return objectMapper.writeValueAsString(obj);
} catch (JsonProcessingException e) {
e.printStackTrace();
}
return null;//or other default value
}
2.B.Define a default value with a single return statement:
private String tryObjMapper(Object obj) {
String retVal = null;//or other default value
try {
retVal = objectMapper.writeValueAsString(obj);
} catch (JsonProcessingException e) {
e.printStackTrace();
}
return retVal ;
}
Consider logging exception using logger and not using e.printStackTrace()
I think that the best way to handle it is to return null at both catch block ant the end of the function. You must check the returnee from the function whether null or not before usage.
Note: This solution is suitable if only you can't change the signature of the function to declare that it throws an exception. Otherwise, go with the signature update.
I have helper class in which I have written this function.
public static String createProject(Map<String, String> params,String projectName, String projectPrefix) {
String createdProject = null;
try {
createdProject=//logic for creating createdProject string which may throw two exception mentioned below
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (TestLinkAPIException t) {
t.printStackTrace();
}
return createdProject;
}
now I am calling this function from GUI part where I have written
String createProject=//called above function.
now If error occur in above code I want to show error to the user.
my question is how I get back the created string and error message if some Exception occur
Create a Custom Exception
Add your String value as an instance field of that Custom Exception.
Throw the custom exception with the String values passed in.
Now you have the exception and the String as well.
If you have a Java 7, then you can use Multi-Catch exception block.
public static String createProject(Map<String, String> params,String projectName, String projectPrefix) throws Exception {
String createdProject = null;
try {
createdProject=//logic for creating createdProject string which may throw two exception mentioned below
} catch (MalformedURLException | TestLinkAPIException e) {
e.printStackTrace();
throw new Exception("Error creating createdProject", e);
}
return createdProject;
}
If exception occurs, createdProject is never set.
You should throw the exception from this method and catch it in block where you calling this method.
public static String createProject(Map<String, String> params,String projectName, String projectPrefix) throws Exception {
String createdProject = null;
try {
createdProject = doSomething();
} catch (Exception e) {
throw new Exception("Error creating Project");
}
return createdProject;
}
and where you calling this method you will have something like this.
try {
String str = createProject();
displayTheProjectCreated(str);
} catch (Exception e) {
// Oops something went wrong
displayErrorMessage(e);
}
I have a small function in java that does a HTTP POST, and returns a JSON Object. This function return the JSON Object.
public JSONObject send_data(ArrayList<NameValuePair> params){
JSONObject response;
try {
response = new JSONObject(CustomHttpClient.executeHttpPost(URL, params).toString());
return response;
} catch(Exception e) {
// do smthng
}
}
This shows me an error that the function must return a JSONObject. how do i make it work? I cant send a JSONObject when there is an error, can I? It would be useless to send a blank jsonobject
This is because you are only returning a JSONObject if everything goes smoothly. However, if an exception gets thrown, you will enter the catch block and not return anything from the function.
You need to either
Return something in the catch block. For example:
//...
catch(Exception e) {
return null;
}
//...
Return something after the catch block. For example:
//...
catch (Exception e) {
//You should probably at least log a message here but we'll ignore that for brevity.
}
return null;
Throw an exception out of the method (if you choose this option, you will need to add throws to the declaration of send_data).
public JSONObject send_data(ArrayList<NameValuePair> params) throws Exception {
return new JSONObject(CustomHttpClient.executeHttpPost(URL, params).toString());
}
You could change it to this:
public JSONObject send_data(ArrayList<NameValuePair> params){
JSONObject response = null;
try {
response = new JSONObject(CustomHttpClient.executeHttpPost(URL, params).toString());
} catch(Exception e) {
// do smthng
}
return response;
}
There's a path through the function that doesn't return anything; the compiler doesn't like that.
You can change this to
catch(Exception e) {
// do smthng
return null; <-- added line
}
or put the return null (or some reasonable default value) after the exception block.
It's reasonble to return 'something' even in an error condition.
Look at JSend for a way to standardize your responses - http://labs.omniti.com/labs/jsend
In my opinion it's easiest to return an error json object and handle that on the client side then to solely rely on HTTP error codes since not all frameworks deal with those as well as they could.
The send_data() method should throw an exception so that the code calling send_data() has control over how it wants to handle the exception.
public JSONObject send_data(ArrayList<NameValuePair> params) throws Exception {
JSONObject response = new JSONObject(CustomHttpClient.executeHttpPost(URL, params).toString());
return response;
}
public void someOtherMethod(){
try{
JSONObject response = sendData(...);
//...
} catch (Exception e){
//do something like print an error message
System.out.println("Error sending request: " + e.getMessage());
}
}
I prefer one entry and one exit. Something like this seems reasonable to me:
public JSONObject send_data(ArrayList<NameValuePair> params)
{
JSONObject returnValue;
try
{
returnValue = new JSONObject(CustomHttpClient.executeHttpPost(URL, params).toString());
}
catch (Exception e)
{
returnValue = new JSONObject(); // empty json object .
// returnValue = null; // null if you like.
}
return returnValue;
}