How to throw an exception for closing resource in try with resources? - exception

I want to try with resources block(PrintWrtiter or FileWriter) to throw an exception on closing resource, So i can print it.
public PrintWriter func throws CustomException{
String filename = "file.txt";
try(PrintWriter feedError = new PrintWriter(new FileWriter(filename ,
true))){
feedError.println("writing in a file");
return feedError;
} catch (Exception e){
e.printStackTrace();
Throwable[] supp = e.getSuppressed();
System.Out.Println(supp);
throw new CustomException("file not found");
}
}
Expecting java.lang.Exception: Error when closing PrintWriter or FileWriter

Related

Junit test cases for delete operation with try and catch block - handling Exception

public UserNoteDefination deleteByNoteCd (UserNoteDefination request, LogDTO log) {
log.setComponent("ClientRequestService.deleteByNoteCd");
UserNoteDefination response new UserNoteDefination();
String tabllame = request.getTabName();
String noteCd-request.getNoteCd();
if (tabName.equalsIgnoreCase("UND_TABLE"))
{
try
userNoteDefRepository.deleteById(noteCd);
response.setMsg("Completed");
log.setPayload("[FROM:UI] clientRequest:Delete Successfully");
loggingService.log(GuiServiceConstants.INFO LEVEL, log);
}
catch (Exception e){
response.setMsg("Error");
log.setPayload("[FROM:UI] clientRequest:Error occured while delete");
loggingService.log(GuiServiceConstants.ERROR LEVEL, log);
}
return response;
}
This is my junit code in mockito
#Test public void deleteByNoteCd() throws Exception {
LogDTO log = new LogDTO(); log.setComponent("ClientRequestService.getClientRequest");
UserNoteDefination response = new UserNoteDefination();
response.setNoteCd("TEST7");
response.setMsg("Completed");
response.setTabName("UND TABLE");
UserNoteDefination rval - service.deleteByNoteCd(response, log);
assertNotNull(rval);
}
I'm unable to cover the exception part. Cab someone help

Junit test cases for delete

public UserNoteDefination deleteByNoted (UserNoteDefination request, LogOTO log) { log.setComponent("ClientRequestService.deleteByNoted") UserNoteDefination response = new UserNoteDefination()
String tablame request.getTabName() String noteCd request.getNoteCd();
if (tablame.equalsIgnoreCase("UND TABLE"))
try (
userNoteDefRepository.deleteById(noteCd); response.setMsg("Completed");
log.setPayload("[FROM:UI] clientRequest:Delete Successfully");
loggingService.log(GuiServicefonstants. INFO LEVEL, log);
catch (Exception e)
response.setMsg("Error");
log.setPayload("[FROH:UI] clientRequest:Error occured while delete");
loggingService.log(GuiServiceConstants.ERROR
I have attached the code

Exception Handling in java to show user the catch error message from the nested method calls

I have doubt in Exception handling in java,when the exception is thrown in the called method, how to show the catch error in the calling method
Yes, it is possible to catch exception inside called method, and then re-throw same exception back to caller method.
public String readFirstLineFromFile(String path) throws IOException {
try {
BufferedReader br = new BufferedReader( new FileReader (path));
StringBuilder lines = new StringBuilder();
String line;
while((line = br.readLine()) != null) {
System.out.println("REading file..." + line);
lines.append(line);
}
return lines.toString();
} catch(IOException ex) {
System.out.println("Exception in called method.." + ex);
throw ex;
}
}
Note: It is not possible if you are using try with resources, and exception occurred inside resources itself like opening of file, or file not found. In that case exception will be directly thrown back to caller.

Test cases using mockito

I have below method of a class.
public Response getProb(long Id) throws ResourceException
{
final Response response = new Response();
JSONObject headerObject = new JSONObject();
String message = null;
int status = 0;
try
{
JSONObject getProb = new JSONObject();
getProb.put("id", Id);
if (commonDao.validateIdCheck(getProb))
{
headerObject.put(CommonConstants.LASTMOD_DATE, commonDao.lastModDate(Id));
response.setResource(headerObject);
message="Retuned Successfully";
}
response.setStatus(message, status);
}
catch (JSONException exception)
{
throw new ResourceException(CommonErrorConstants.JSON_EXCEPTION, exception);
}
catch (ResourceException exception)
{
throw exception;
}
catch (Exception exception)
{
throw new ResourceException(CommonErrorConstants.GENERAL_EXCEPTION, exception);
}
return response;
}
what will be the junit test cases using mockito which will give 100% code coverage.
These are the cases you can test and achieve 100% coverage:
validateIdCheck returns true
validateIdCheck returns false
your try block throws JSONException
your try block throws ResourceException
your try block throws Exception
a success case where you return a response

Parameter passing via httpgetClient

I need to hit the URL and get the response, but through this method I can get only one message whereas I want to pass multiple values as a response.
Here is the method:
public String getOutputFromUrl(String url)
{
Log.d("in getOutputFromUrl", "getOutputFromUrl");
String[] output = null;
try {
httpClient = new DefaultHttpClient();
httpGet = new HttpGet(url);
httpResponse = httpClient.execute(httpGet);
httpEntity = httpResponse.getEntity();
output = EntityUtils.toString(httpEntity);
} catch (UnsupportedEncodingException e) {
Log.d("in UnsupportedEncodingException", e.toString());
e.printStackTrace();
} catch (ClientProtocolException e) {
Log.d("in geClientProtocolExceptiontOutputFromUrl", e.toString());
e.printStackTrace();
} catch (IOException e) {
Log.d("in getOutputFromUrl", e.toString());
e.printStackTrace();
}
Log.d("in getOutputFromUrl:output===>>", output);
return output;
}
I want the return type of the method to be String[] or object of any class ,but
output = EntityUtils.toString(httpEntity)
This line accepts only a string; no other object or string array, so I can't keep multiple values in this output variable passed as response from the URL link